So suppose we want to produce the list [0, 1, -1, 2, -2, ...
in Haskell.
What is the most elegant way of accomplishing this?
I came up with this solution:
solution = [0] ++ foldr (\(a,b) c->a:b:c) [] zip [1..] $ map negate [1..]
But I am sure there must be a better way.
This seems like the kind of thing that comprehensions are made for:
solution = 0 : [y | x <- [1..], y <- [x, -x]]
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