0
比方說,我有這樣的一段代碼:如果我知道結果是一個整數,但是ghc不確定怎麼辦?
demo::Integer -> Integer
demo x = x*(x+1)/2
main = do print $ demo 8
顯然,結果是一個整數x或它的繼任者是偶數。
理解編譯器只着眼於/
並說
[1 of 1] Compiling Main (debug.hs, debug.o)
debug.hs:2:17:
No instance for (Fractional Integer) arising from a use of `/'
Possible fix: add an instance declaration for (Fractional Integer)
In the expression: x * (x + 1)/2
In an equation for `demo': demo x = x * (x + 1)/2
但是據我所知Integer
不是Fractional
一部分。 如何保持簽名Integer -> Integer
?
你不能在整數中使用'/'。試試''demo x = x *(x + 1)'div' 2'' – pdexter
謝謝,這就是我所需要的!如果你讓它成爲答案,我會接受它。 – peer
還請記住*數學數字*和它們在編程語言中的實現之間存在差異。僅僅因爲你可以在數學上證明某個表達式總是一個整數並不意味着當你試圖用一種編程語言來計算它時,你實際上會得到一個整數。這取決於實施。 – Bakuriu