我正在尝试使用Haskel实现collat​​z-list:
这是我的代码:

collatz n
     | mod n 2 == 0 = div n 2
     | otherwise =  3 * n + 1


collatzList n
        | n < 1 = error "Cannot have negative number"
collatzList
        | n == 1 = [n]
        | otherwise = n:collatzList (collatz n)

我收到的错误消息是这样的:
解析输入“collat​​zList”上的错误
[1 of 1]编译Main(exer.hs,已解释)
失败,模块已加载:无。

谁能告诉我为什么我收到此消息?

最佳答案

我收到不同的错误(使用GHC 7.4.1):

> :load "/tmp/C.hs"
[1 of 1] Compiling Main             ( /tmp/C.hs, interpreted )

/tmp/C.hs:9:11: Not in scope: `n'

/tmp/C.hs:9:21: Not in scope: `n'

/tmp/C.hs:10:23: Not in scope: `n'

/tmp/C.hs:10:46: Not in scope: `n'
Failed, modules loaded: none.

这是因为您忘记了n的第二个方程式中的collatzList参数。您可以添加此参数
collatzList n
        | n < 1 = error "Cannot have negative number"
collatzList n -- the n was missing here
        | n == 1 = [n]
        | otherwise = n:collatzList (collatz n)

或者,由于左侧现在相同,因此您只需将其与第一个连接即可:
collatzList n
        | n < 1 = error "Cannot have negative number"
        | n == 1 = [n]
        | otherwise = n:collatzList (collatz n)

10-06 02:44