cyberdot
cyberdot

Reputation: 177

Best way to implement outer / inner loop in Elixir

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.

Upvotes: 3

Views: 412

Answers (3)

Kevin Montuori
Kevin Montuori

Reputation: 61

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.

Upvotes: 6

bitwalker
bitwalker

Reputation: 9261

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

Upvotes: 6

Paweł Obrok
Paweł Obrok

Reputation: 23164

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)

Upvotes: 5

Related Questions