使用haskell的collatz-list实现 [英] collatz-list implementation using haskell
问题描述
我正在尝试使用Haskel实现collatz-list: 这是我的代码:
I am trying to implement collatz-list using Haskel: Here's my code:
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)
我收到的错误消息是: 解析输入"collatzList"上的错误 [1 of 1]编译Main(exer.hs,已解释) 失败,模块已加载:无.
The error message I am getting is this: parse error on input `collatzList' [1 of 1] Compiling Main ( exer.hs, interpreted ) Failed, modules loaded: none.
有人可以告诉我为什么收到此消息吗?
Can anyone tell me why I am getting this message?
推荐答案
我遇到了其他错误(使用GHC 7.4.1):
I get different errors (using 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.
这是因为您忘记了collatzList
的第二个方程式中的n
自变量.您可以添加此参数
This is because you forgot the n
argument in your second equation for collatzList
. You can either add this argument
collatzList n
| n < 1 = error "Cannot have negative number"
collatzList n -- the n was missing here
| n == 1 = [n]
| otherwise = n:collatzList (collatz n)
或者,由于左侧现在相同,因此您可以简单地将其与第一个连接起来:
or, since the left hand sides are now the same, you can simply join it with the first one:
collatzList n
| n < 1 = error "Cannot have negative number"
| n == 1 = [n]
| otherwise = n:collatzList (collatz n)
这篇关于使用haskell的collatz-list实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!