我是 Haskell 的新手,一般来说是编程。我正在尝试定义一个从n生成 Collatz 数字序列的函数。我有:
collatz n = (collatz' n) : 1
where collatz' n = (takeWhile (>1) (collatz'' n))
where collatz'' n = n : collatz'' (collatz''' n)
where collatz''' 1 = 1
collatz''' n = if (even n) then (div n 2) else ((3*2)+1)
当我在 GHCi 中运行它时,我得到了错误:
No instance for (Num [t])
arising from the literal `2' at <interactive>:1:7
Possible fix: add an instance declaration for (Num [t])
我不知道这是什么意思。问题似乎是将“1”附加到列表中。出现这个问题是因为
collatz' n = (takeWhile (>0) (collatz'' n))
在正确的 Collatz 序列之后生成无限的“1”序列;然而,
collatz' n = (takeWhile (>1) (collatz'' n))
从n中生成除 "1" 之外的所有 Collatz 数。我究竟做错了什么?