类型错误
问题描述:
我试图让这片Haskell代码的工作,但我不断收到此错误信息:类型错误
> 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
下面的代码:
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))))
任何想法如何要解决这个问题?
答
问题是div
在最后一行。
当你想做一个函数中缀时,你必须在`之间编写它。所以,简单地改变最后一行:您正在使用div
作为缀
| otherwise = ((fact n) `div` ((fact m) * (fact (n - m))))
+0
啊排序吧,非常感谢:) – Yawn
答
,而是让你必须把它写这样它不是一个运营商:
comb :: Int -> Int -> Int
comb n m
| n < m = error "undefined as n < m"
| otherwise = fact n `div` (fact m * fact (n - m))
或像这样:
comb :: Int -> Int -> Int
comb n m
| n < m = error "undefined as n < m"
| otherwise = div (fact n) (fact m * fact (n - m))
答
你有
| otherwise = ((fact n) div ((fact m) * (fact (n - m))))
但应
| otherwise = ((fact n) `div` ((fact m) * (fact (n - m))))
(至少)
基本上,您使用的是管道符,你必须使用反引号来标记它。
然而,在这种情况下,为了减少括号的数量,我把它改写为
| otherwise = div (fact n) $ (fact m) * (fact (n - m))
编辑:s/inline/infix
你可以写'fact'短,例如'事实n =产品[1..n]'。 – Landei