我试图在Haskell中实现一个铃号查找器+求和。我相信我的方法是正确的,但我在编译时遇到了一些错误。我当前的错误消息是:
[1 of 1] Compiling Main ( survey2.hs, survey2.o )
survey2.hs:5:14:**
Expected a constraint, but ‘Integer’ has kind ‘*’
In the type signature for ‘binomial’:
binomial :: (Integer, Integer) => Integer
survey2.hs:15:12:
Expected a constraint, but ‘Integer’ has kind ‘*’
In the type signature for ‘bellSum’: bellSum :: Integer => Integer**
我对haskell和全新的函数式语言都是新手。基于此错误,我尝试更改我的"函数定义" (或者你在Haskell中称之为的任何东西),但我似乎只会导致更多错误。
该计划的最终目标是打印铃号0-9的总和。
factorial n
| n <= 1 = 1
| otherwise = n * factorial(n-1)
binomial :: (Integer, Integer) => Integer
binomial n k
| k > n = 0
| k < 0 = 0
| otherwise = factorial(n) / factorial(n-k) * factorial(k)
bell n
| n <= 1 = 1
| otherwise = sum [ binomial (n-1, k-1) * bell (k-1) | k<-[0..n-1] ]
bellSum :: Integer => Integer
bellSum n = sum [ bell(k) | k<-[0..n] ]
main = bell(9 :: Integer)
答案 0 :(得分:1)
请注意,这不一致(=>
应为->
)
binomial :: (Integer, Integer) -> Integer
binomial n k
要么改为
binomial :: Integer -> Integer -> Integer
binomial n k
或
binomial :: (Integer, Integer) -> Integer
binomial (n, k)
另一个提示,你可以在没有因子函数(甚至乘法)的情况下计算二项式
binomial n k | k==0 || k==n = 1
| k==1 = n
| otherwise = binomial (n-1) (k-1) + binomial (n-1) k
这仍然非常低效,但可以记忆。