Generating Infinite List in Haskell

410 views Asked by At

So, been going over some old exams in preparation for my upcoming one and came across this question:

Write Haskell code to define ints :: [Int] an infinite list of the following form: [0, 1, -1, 2, -2, 3, -3, 4, -4..]

I've been plugging at it for the past half an hour but can't seem to find anything to solve it or that will do what I want. I get the feeling that what I am really wanting is a list comprehension of the form

ints :: [Int]
ints = [0] ++ [x (-x) | x <- [1..]]

But this doesn't work and I'm unsure of how to get it to work

1

There are 1 answers

11
Johannes Weiss On BEST ANSWER

The problem is that x (-x) is not of type Int (thanks to @leftaroundabout removed non-sense about non-valid syntax here). You want to generate two values for every x. So I guess the easiest way is to create lots of list pairs [1, -1], [2, -2], ... and then to concatenate them all together. And obviously prepend a 0.

ints :: [Int]
ints = 0 : concat [[x, (-x)] | x <- [1..]]

Also, you might want to use Integer instead of Int as Int will overflow at some point but Integer won't.