Вопрос

I am trying to generate a list of infinite numbers

0,1,-2,3,-4,5,-6...

So far I got

evenise x   | x == 0 = 0
            | even x = -x
            | otherwise = x

s = foldl (\x -> evenise x) 0 [1..]

However I am getting the error

Occurs check: cannot construct the infinite type: a0 = b0 -> a0
In the first argument of `evenise', namely `x'
In the expression: evenise x
In the first argument of `foldl', namely `(\ x -> evenise x)'

I do not understand the error since evenise takes in an element, and the anoymous function (\x -> evenise x) also takes in a single element.

Это было полезно?

Решение

You want to use map not foldl

s = map evenise [0..]

map goes through a list and applies the mapped function to each element. foldl is used for "reducing" a list into a value--for example, adding all the elements in a list can be done like

foldl (+) 0

also, foldl only works on finite lists, while foldr (also for reducing) will sometimes work on infinite lists.

Другие советы

You're getting an error because foldl takes a function of two arguments, not one. But foldl can't handle infinite lists anyway, so I don't understand what you're trying to do there.

(You don't need the first line in evenise because -0 == 0.)

You can also create an infinite list and embed the test into the list definition:

s = [ if odd x then x else negate x | x <- [0,1..] ]
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top