我在执行这个递归函数时做错了什么?

时间:2015-12-26 11:12:44

标签: haskell recursion

到目前为止,这是我的代码:

test n p
  |p > n  = 0
  |p == n = 1
  |otherwise = sum [test n-p q|q<-[1..p+1]]

这应该实现一个简单的递归函数(接受非负整数)

enter image description here

但是我收到一条我不明白的错误消息。 (我无法从ghci控制台复制它,所以在这里我只是输入它)有谁能告诉我这里有什么问题?

Expected a constraint, but 'Int' has kind '*'
In the type signature for 'test': test :: Int -> Int => Int

2 个答案:

答案 0 :(得分:3)

sum [test n-p q|q<-[1..p+1]]

函数应用程序在Haskell中具有非常高的优先级。以上解析为:

sum [ (test n) - (p q) |q<-[1..p+1]]

以上test用作返回数字的一元函数,p也用作返回数字的一元函数。这会触发类型错误。

另请注意,类型签名中的=>错误:

test :: Int -> Int => Int
--                ^^^^

以上原因导致GHC尝试解析左侧部分Int -> Int,就像它是类约束一样,但它是一种类型(“有类*”,在技术术语中)所以错误是报道。

答案 1 :(得分:1)

test n p
  |p > n  = 0
  |p == n = 1
  |otherwise = sum [test (n-p) q|q<-[1..p+1]]

即。括号(n-p)

相关问题