In Erlang, list comprehensions are used to make new lists
out of old ones.
||
.||
is the qualifier, either a generator or a filter.Generator
: It extracts
each element from the List
, one by one. It is written as a Pattern.Filter:
It filters the elements of the list. It can be a boolean expression.[X || X <- [1,7,z,9,4,b,2,6], X > 5].
This should be read like this:
Expression: X
Generator: X <- [1,7,z,9,4,b,2,6]
Filter: X > 5
-module(main).-export([main/0]).main() ->OldList = [1,7,z,9,4,b,2,6],io:fwrite("OldList:~w~n",[OldList]),%List comprehensionio:format("Get the elements greater than 5 from OldList~n", []),GreaterThan5=[X || X <- [1,7,z,9,4,b,2,6], X > 5],io:fwrite("GreaterThan5:~w~n",[GreaterThan5]),io:format("Get the odd elements from OldList~n", []),Odds = [X || X <- OldList, X rem 2 =/= 0],io:format("Odds:~p~n", [Odds]),io:format("Get the elements that are odd and greater than 5 from OldList~n", []),NewList_Odd_GreaterThan5 = [X || X <- OldList, X rem 2 =/= 0, X > 5],io:format("NewList_Odd_GreaterThan5:~p~n", [NewList_Odd_GreaterThan5]).
Lines 8 to 10: We print the elements greater than five from OldList
using list comprehension.
Lines 12 to 14: We print the odd elements from OldList
using list comprehension.
Lines 16 to 18: We print the elements that are odd and greater than 5 from OldList
using list comprehension.