Haskell-在无限流中否定偶数



我正在尝试生成无限数字的列表

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

到目前为止,我得到了

evenise x   | x == 0 = 0
            | even x = -x
            | otherwise = x
s = foldl (x -> evenise x) 0 [1..]

但是我收到错误

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)'

我不明白这个错误,因为evenise接受一个元素,而 anoymous 函数(x -> evenise x)也接受单个元素。

你想使用map而不是foldl

s = map evenise [0..]

map遍历列表并将映射的函数应用于每个元素。 foldl用于将列表"还原"为值 - 例如,添加列表中的所有元素可以像

foldl (+) 0

此外,foldl仅适用于有限列表,而foldr(也用于归约)有时适用于无限列表。

你得到一个错误,因为它foldl两个参数的函数,而不是一个。但是foldl无论如何都无法处理无限的列表,所以我不明白你想在那里做什么。

(您不需要evenise的第一行,因为 -0 == 0。

您还可以创建一个无限列表并将测试嵌入到列表定义中:

s = [ if odd x then x else negate x | x <- [0,1..] ]

最新更新