我需要定義一個Haskell函數:哈斯克爾只允許正輸入
func :: Int -> Int
func 1 = 1
func 2 = 2
func x = x+1
因此,它只允許正數。我已經有一個看一個類似的問題:Non-negative integers
寫了這樣:
newtype Positive a = Positive a
toPositive :: (Num a, Ord a) => a -> Positive a
toPositive x
| x < 0 = error "number cannot be negative"
| otherwise = Positive x
func :: Positive a -> a
func (Positive n) = n
然而這已經引發錯誤。思考?
更新:
錯誤示例:
*Main> func 1
<interactive>:32:6:
No instance for (Num (Positive a0)) arising from the literal `1'
Possible fix: add an instance declaration for (Num (Positive a0))
In the first argument of `func', namely `1'
In the expression: func 1
In an equation for `it': it = func 1
*Main>
它對我來說非常合適。你得到什麼錯誤? –
以上樣本誤差更新 – Dario
嘗試調用'$ FUNC 1' toPositive –