Reading — step 1 of 5
Learn
~1 min readFunctions and Pattern Matching
Lists are written with [] and elements separated by ,. The [H | T] syntax destructures into head and tail:
L = [1, 2, 3, 4, 5],
length(L), % 5
hd(L), % 1
tl(L), % [2, 3, 4, 5]
lists:nth(3, L), % 3 (1-indexed!)
lists:reverse(L), % [5, 4, 3, 2, 1]
lists:sort(L) % [1, 2, 3, 4, 5]
List comprehensions generate new lists from existing ones — like Python's:
[X * X || X <- [1, 2, 3, 4, 5]] % [1, 4, 9, 16, 25]
[X || X <- [1,2,3,4,5,6,7,8,9,10], X rem 2 =:= 0] % [2, 4, 6, 8, 10]
The syntax is [Expr || Generator, Filter, ...]. Multiple generators give Cartesian products.
lists module has the functional toolkit:
lists:map(fun(X) -> X * 2 end, [1, 2, 3]), % [2, 4, 6]
lists:filter(fun(X) -> X > 2 end, [1, 2, 3, 4]), % [3, 4]
lists:foldl(fun(X, Acc) -> X + Acc end, 0, L) % sum
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…