2011-09-27 174 views
0

我試圖讓這片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)))) 

任何想法如何要解決這個問題?

+0

你可以寫'fact'短,例如'事實n =產品[1..n]'。 – Landei

回答

5

問題是div在最後一行。

當你想做一個函數中綴時,你必須在`之間編寫它。所以,簡單地改變最後一行:您正在使用div作爲綴

| otherwise = ((fact n) `div` ((fact m) * (fact (n - m)))) 
+0

啊排序吧,非常感謝:) – Yawn

2

,而是讓你必須把它寫這樣它不是一個運營商:

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)) 
0

你有

| 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