by Example

List Comprehension


List comprehensions are used to generate new lists
from existing ones.








The left side of `||` can be any expression.
The right part, `X <- L` is called a generator, and it extracts
each element from `L`, one by one.




In addition to the generator, a list comprehension can
also have one or more filters.




-module(list_comp).
-compile(export_all).


run() ->
    L = [1,2,3,4,5],




    LL = [X*X || X <- L],
    io:format("~p~n", [L]),
    io:format("~p~n", [LL]),



    Evens = [X || X <- L, X rem 2 == 0],
    io:format("~p~n", [Evens]).
1> c(list_comp).
{ok,list_comp}

2> list_comp:run().
[1,2,3,4,5]
[1,4,9,16,25]
[2,4]
ok


Next: Custom Behaviors