Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Produce the infinite list [0, 1, -1, 2, -2, ... in Haskell

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.

like image 442
Jsevillamol Avatar asked Jan 06 '18 17:01

Jsevillamol


1 Answers

This seems like the kind of thing that comprehensions are made for:

solution = 0 : [y | x <- [1..], y <- [x, -x]]
like image 150
Chris Martin Avatar answered Sep 28 '22 06:09

Chris Martin