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
The problem is that
x (-x)
is not of typeInt
(thanks to @leftaroundabout removed non-sense about non-valid syntax here). You want to generate two values for everyx
. 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 a0
.Also, you might want to use
Integer
instead ofInt
asInt
will overflow at some point butInteger
won't.