I wrote a blog post about 3 different ways to build a list with conditional elements in Elixir (and what that has to do with application startup).
1 Like
Corresponding tweet for this thread:
Share link for this tweet.
1 Like
There are other ways to achieve such results for example using recursive functions.
defmodule Example do
def sample(list) do
List.foldr(list, [], fn
{false, _child_spec}, acc -> acc
{true, child_spec}, acc -> [child_spec | acc]
child_spec, acc -> [child_spec | acc]
end)
end
def sample2([]), do: []
def sample2([{false, _child_spec} | rest]), do: sample2(rest)
def sample2([{true, child_spec} | rest]), do: sample2([child_spec | rest])
def sample2([child_spec | rest]), do: [child_spec | sample2(rest)]
end
input = [:not_tuple, {false, :skip_me}, {true, :no_skip}]
Example.sample(input)
Example.sample2(input)
Helpful resources:
2 Likes