flawr
flawr

Reputation: 11638

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)

enter image description here

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

Upvotes: 0

Views: 114

Answers (2)

chi
chi

Reputation: 116174

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.

Upvotes: 3

phadej
phadej

Reputation: 12133

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

I.e. parentheses around (n-p)

Upvotes: 1

Related Questions