anishjp
anishjp

Reputation: 115

What does [ ... || ... <- ...] do in this snippet of code?

I need your help again, I am trying to understand this piece of erlang code.

Line="This is cool".
Lines = [Line || _Count <- lists:seq(1,5)].

output is

["This is cool","This is cool","This is cool","This is cool","This is cool"]

I don't understand the logic behind it printing the required number of times. What does Line || _***** means?

Upvotes: 2

Views: 120

Answers (3)

Pascal
Pascal

Reputation: 14042

it can be read like this: NewListe = [Dosomething || Element <- Liste]

create a NewListe this way: for each Element of Liste, build a new element with Dosomething.

Step by step it gives Liste = lists:seq(1,5) = [1,2,3,4,5];

for each Element, just discard the value of element (it is why it is written as _Count) and

Dosomething is only send back the value "This is cool",

and the result is a list of 5 times "This is cool"

["This is cool","This is cool","This is cool","This is cool","This is cool"]

<- is called a generator; after the sign || you may have generators or filters. For example if we imagine that you have a list of different elements and want to get only the printable list items, turned to upper case, you will need a generator:

X <- ["toto",5,"Hello",atom] to get each element

a filter:

io_lib:printable_list(X) to select only the printable lists

and a transformation:

string:to_upper(X) to turn to upper case

all together you have what is expected:

1> [string:to_upper(X) || X <- ["toto",5,"Hello",atom], io_lib:printable_list(X)].
["TOTO","HELLO"]
2>

Upvotes: 0

Dmitry Belyaev
Dmitry Belyaev

Reputation: 2593

Look at this piece of code:

Line = "This is cool".
Lines = [{Line, Count} || Count <- lists:seq(1, 5)].

Here you create a list of tuples of size 2 where first element is constant and the second is taken from the source list of list comprehension. And if you remove an element from the tuple it won't change list's structure.

Upvotes: 2

Doug Currie
Doug Currie

Reputation: 41170

Since the value of Line is not changed in the right hand side of the list comprehension, the value of each element is the same, the value of Line.

The right side of the list comprehension is just determining the number of elements.

Upvotes: 2

Related Questions