Elixir Language List Comprehensions


Example

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:

  • create new lists
iex(1)> for value <- [1, 2, 3], do: value + 1
[2, 3, 4] 
  • filtering lists, using 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]
  • create custom map, using into keyword:
iex(4)> for value <- [1, 2, 3], into: %{}, do: {value, value + 1}
%{1 => 2, 2=>3, 3 => 4}

Combined example

iex(5)> for value <- [1, 2, 3], odd?.(value), into: %{}, do: {value, value * value}
%{1 => 1, 3 => 9}

Summary

List Comprehensions:

  • uses for..do syntax with additional guards after commas and into keyword when returning other structure than lists ie. map.
  • in other cases return new lists
  • doesn't support accumulators
  • can't stop processing when certain condition is met
  • guard statements have to be first in order after for and before do or into symbols. Order of symbols doesn't matter

According 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.