Elixir doesn't have loops. Instead of them for lists there are great Enum
and List
modules, but there are also List Comprehensions.
List Comprehensions can be useful to:
iex(1)> for value <- [1, 2, 3], do: value + 1
[2, 3, 4]
guard
expressions but you use them without when
keyword.iex(2)> odd? = fn x -> rem(x, 2) == 1 end
iex(3)> for value <- [1, 2, 3], odd?.(value), do: value
[1, 3]
into
keyword:iex(4)> for value <- [1, 2, 3], into: %{}, do: {value, value + 1}
%{1 => 2, 2=>3, 3 => 4}
iex(5)> for value <- [1, 2, 3], odd?.(value), into: %{}, do: {value, value * value}
%{1 => 1, 3 => 9}
List Comprehensions:
for..do
syntax with additional guards after commas and into
keyword when returning other structure than lists ie. map.guard
statements have to be first in order after for
and before do
or into
symbols. Order of symbols doesn't matterAccording to these constraints List Comprehensions are limited only for simple usage. In more advanced cases using functions from Enum
and List
modules would be the best idea.