简体   繁体   中英

What am I doing wrong in the implementation of this recursive function?

This is my code so far:

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

This should implement a simple recursive function (accepting nonnegative integers)

在此处输入图片说明

However I do get an error message that I do not understand. (I was not able to copy it from the ghci console, so here I just typed it out) Can anyone tell me what is wrong here?

Expected a constraint, but 'Int' has kind '*'
In the type signature for 'test': test :: Int -> Int => Int
sum [test n-p q|q<-[1..p+1]]

Function application has a very high precedence in Haskell. The above is parsed as:

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

Above test is used as a unary function returning a number, and p is also used as a unary function returning a number. This triggers a type error.

Also, note that the => is wrong in the type signature:

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

The above causes GHC to try parsing the left part Int -> Int as if it were a class constraint, but it is a type ("has kind * ", in technical terms) so an error is reported.

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

Ie parentheses around (np)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM