3

What would be the best / correct way to implement the following code in Elixir:

 foreach( var item in items) {

  foreach(var num in get_nums_from(item)) {

        yield return is_valid(num) ? num : -1;
 }  }

Many thanks.

3 Answers 3

6

Another approach, assuming laziness is not a requirement, is a list comprehension:

for item <- items, num <- get_nums_from(item) do if is_valid?(num), do: num, else: -1 end

Sign up to request clarification or add additional context in comments.

Comments

6

Bitwalker's response answers your question nicely; however, what are you doing with all those -1s? If you're just going to filter them out later, consider something like:

for i <- items, num <- get_nums_from(item), is_valid?(num), do: num

In executable terms that looks like

iex(2)> for i <- [[1,2,3],[4,5,6],[7,8,9]], j <- i, rem(j, 2) == 0, do: j
[2, 4, 6, 8]

Or maybe give a look at Enum.filter/2.

Comments

5

A free translation of the loop will be something like:

Enum.flat_map(items, fn (item) ->
  Enum.map(get_nums_from(item), fn (num) ->
    if is_valid?(num), do: num, else: -1
  end)
end)

If you also want to preserve the lazy character of the iteration (which I think the .net version will have) you need to use Stream instead, to create a lazy sequence:

Stream.flat_map(items, fn (item) ->
  Stream.map(get_nums_from(item), fn (num) ->
    if is_valid?(num), do: num, else: -1
  end)
end)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.