Reputation: 33
I have to create a recursive function that takes in two numbers (n and k) and gives back their binomial coefficient.
I have to use pascal :: Int -> Int -> Int
I honestly don't understand where it went wrong, thanks for the help!
pascal :: Int -> Int -> Int
pascal n k
| k == 0 = 1
| n == n = 1
| k > n = 0
| otherwise = pascal(n-1)(k-1) + pascal(n-1) + k
The following error is:
main.hs:7:40: error:
• Couldn't match expected type ‘Int’ with actual type ‘Int -> Int’
• Probable cause: ‘pascal’ is applied to too few arguments
In the second argument of ‘(+)’, namely ‘pascal (n - 1)’
In the first argument of ‘(+)’, namely
‘pascal (n - 1) (k - 1) + pascal (n - 1)’
In the expression: pascal (n - 1) (k - 1) + pascal (n - 1) + k
|
7 | | otherwise = pascal(n-1)(k-1) + pascal(n-1) + k
| ^^^^^^^^^^^
<interactive>:3:1: error:
• Variable not in scope: main
• Perhaps you meant ‘min’ (imported from Prelude)
Upvotes: 2
Views: 425
Reputation: 476659
As the exception says, pascal (n-1)
does not make much sense, since that is a function Int -> Int
, so you can not add pascal (n-1) (k-1)
and pascal (n-1)
together.
You thus need to pass an extra parameter. For example:
pascal :: Int -> Int -> Int
pascal _ 0 = 1
pascal n k
| k == n = 1
| k > n = 0
| otherwise = pascal (n-1) (k-1) + pascal (n-1) k
Note that the condition n == n
is always true, you probably want to say n == k
?
Upvotes: 5