2013-06-29 23 views
2

其他問題和問題雖然相似,但並不完全像這樣。在這個特定的編譯器錯誤中,Haskell GHC不會編譯下面的代碼,原因如下。我完全不理解 - 代碼非常簡單。沒有使用`>'引起的(Ord int)的實例,Haskell

--factorial 

fact :: int -> int 
fact 0 = 1 
fact n | n > 0 = n * fact(n - 1) 

main = print (fact 10) 

(錯誤:)

No instance for (Ord int) arising from a use of `>' 
Possible fix: 
add (Ord int) to the context of 
the type signature for fact :: int -> int 
In the expression: n > 0 
In a stmt of a pattern guard for 
an equation for `fact': 
n > 0 
In an equation for `fact': fact n | n > 0 = n * fact (n - 1) 

你能解釋一下這個問題給我嗎?

回答

4

Int是你想要什麼:

fact :: int -> int 

- >

fact :: Int -> Int 

由於在Haskell,類型需要開始用帽。

編輯:感謝Yuras的評論是:

或者,如果你願意,你可以用一個類型類:

fact :: Integral a => a -> a 

而且你可以命名類型變量無論你喜歡,包括int。另外,如果要定義一般數字的階乘,則Num可能更適合您的目的。

+0

爲什麼'Num int => int - > int'? :) – Yuras

+1

@Yuras嗯,這更好 - 我寧願'積分',但很好的提示! –

+0

* facepalm *謝謝。這是我用Haskell編寫和編譯的第一個程序(包含一個函數)。 – bimmo

相關問題