Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is adding multiple elements in a list comprehension possible?

I'm wondering whether it's possible to add multiple elements to a list within a list comprehension.

For instance, if I want a list consisting of the numbers 1 to 10, I can write:

[k | k <- [1..10]]

However, is there also a way to do this by always adding k and k+1 in the same step, and just take only the odd numbers k? Following code is invalid but perhaps explains better what I'm trying to do:

[k, k+1 | k <- [1, 3..10]]

Currently, the closest thing to this (that I am aware of) is the following:

foldl1 (++) [[k, k + 1] | k <- [1, 3..10]]
like image 661
flawr Avatar asked May 01 '16 09:05

flawr


1 Answers

There are some alternatives, none of which is significantly better than what you propose.

concat [ [k, k+1] | k <- [1, 3 .. 10] ]
join   [ [k, k+1] | k <- [1, 3 .. 10] ]
[ x | k <- [1, 3 .. 10], x <- [k,k+1] ]
[1, 3 .. 10] >>= (\x -> [x, x + 1])
do x <- [1, 3 .. 10] ; [x, x+1]

Note that foldl1 (++), as in your solution, will abort the program with a runtime error if it finds an empty lists-of-lists. The above alternatives have no such problem.

like image 170
chi Avatar answered Oct 14 '22 18:10

chi