Elixir: List Comprehension

Using a Comprehension to Iterate through a List

nick3499
1 min readJul 16, 2017
Elixir: List Comprehensions

The comprehension below iterates through each item in the list [1, 2, 3, 4]. Passing each numerical value to the anonymous function's n attribute. Next, each item is squared n * n. Finally, the for loop returns a list of squared values [1, 4, 9, 16].

iex(1)> for n <- [1, 2, 3, 4], do: n * n
[1, 4, 9, 16]

The comprehension below mimics the comprehension above, with the exception of the 1..4 range below replacing the [1, 2, 3, 4] list above. To demonstrate the difference between brevity below and clarity above.

iex(2)> for n <- 1..4, do: n * n
[1, 4, 9, 16]

--

--

nick3499
nick3499

Written by nick3499

coder of JavaScript and Python

No responses yet