Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does || mean in Erlang?

Tags:

erlang

I found that there is a || in list manipulation. What does the || mean? Are there any examples about ||?

lists:sum([A*B || {A, B} <- Foo]).
like image 427
why Avatar asked May 11 '11 09:05

why


People also ask

Which symbol is used to declare unbound values in Erlang?

In Erlang, all the variables are bound with the '=' statement. All variables need to start with the upper case character. In other programming languages, the '=' sign is used for the assignment, but not in the case of Erlang. As stated, variables are defined with the use of the '=' statement.


2 Answers

It is used in List comprehensions. List comprehensions is a shorter way to create lists without having to use funs, maps or filters.

From Programming Erlang:

If we have a list L:

L = [1,2,3,4,5].

And we want to double every element, we can do:

lists:map(fun(X) -> 2*X end, L).

But with List comprehensions we can do:

[2*X || X <- L].
like image 160
Jonas Avatar answered Sep 28 '22 10:09

Jonas


Nomenclature most likely comes from mathematical notion of sets, where || means "such that".

e.g. copied from Wikipedia

F = {n2 − 4 : n is an integer; and 0 ≤ n ≤ 19}

In this notation, the colon (":") means "such that", and the description can be interpreted as "F is the set of all numbers of the form n2 − 4, such that n is a whole number in the range from 0 to 19 inclusive." Sometimes the vertical bar ("|") is used instead of the colon.

Applying same thing to

lists:sum([A*B || {A, B} <- Foo]).

means:- generate A*B such that A and B belong to list of tuples "Foo"

like image 42
spkhaira Avatar answered Sep 28 '22 11:09

spkhaira