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]]
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With