Type error in application
I'm 开发者_开发知识库trying to get this piece of haskell code to work, however I keep getting this error message:
> ERROR file:.\4.hs:9 - Type error in application
> Expression : fact n div (fact m * fact (n - m))
> Term : fact
> Type : Int -> Int
> Does not match : a -> b -> c -> d
Here's the code:
fact :: Int -> Int
fact q
| q == 1 = 1
| otherwise = q * fact(q-1)
comb :: Int -> Int -> Int
comb n m
| n < m = error "undefined as n < m"
| otherwise = ((fact n) div ((fact m) * (fact (n - m))))
Any idea how to fix it?
The problem is div
in the last line.
When you want to make a function infix, you have to write it between `. So, simply change the last line to:
| otherwise = ((fact n) `div` ((fact m) * (fact (n - m))))
You are using div
as infix, but it is not an operator so you have to write it like this:
comb :: Int -> Int -> Int
comb n m
| n < m = error "undefined as n < m"
| otherwise = fact n `div` (fact m * fact (n - m))
or like this:
comb :: Int -> Int -> Int
comb n m
| n < m = error "undefined as n < m"
| otherwise = div (fact n) (fact m * fact (n - m))
You have
| otherwise = ((fact n) div ((fact m) * (fact (n - m))))
but it should be
| otherwise = ((fact n) `div` ((fact m) * (fact (n - m))))
(at least)
Basically, you are using an infix operator, you'll have to mark it using back-quotes.
However, in this case, to reduce the number of parantheses, I'll rewrite it as
| otherwise = div (fact n) $ (fact m) * (fact (n - m))
Edit: s/inline/infix
精彩评论