Best way to implement outer / inner loop in Elixir

What's 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


source to share


3 answers


Free translation of the cycle will be something like this:

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 keep the lazy nature 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)

      

+5


source


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

+6


source


The beatwaker answer answers your question beautifully; however, what are you doing with all those -1S? If you are going to filter them later, think of something like:

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

      

In executable expressions that look 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 take a look at Enum.filter / 2.

+6


source







All Articles