2014-05-01 64 views
0

我需要定義一個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> 
+0

它對我來說非常合適。你得到什麼錯誤? –

+0

以上樣本誤差更新 – Dario

+2

嘗試調用'$ FUNC 1' toPositive –

回答

2

你忘了打電話給toPositiveInt轉換爲Positive。這樣稱呼:

func $ toPositive 1 

此外,Haskell的一個怪癖是其處理負數文字。爲避免與減法操作符混淆,必須將它們包裝在圓括號中:

func $ toPositive (-1) 
+0

謝謝,是的,這工作:)有沒有什麼辦法,我可以避免調用「$ toPositive」,只使用「func(-1)」? – Dario

+0

此外,當我嘗試添加「func 0 = 0」或「func(正0)= 0」我得到... dynprog.hs:9:16: 沒有實例(數字a) 「 可能的修正: 加載(民a)至 上下文爲FUNC類型簽名::正一 - >一個 在模式:0 在模式:正0 在用於'FUNC等式」: func(正0)= 2 失敗,加載模塊:無。 – Dario

+0

您可以編寫一個新的'func',它將'Int'作爲參數,並在內部調用正文。然而,這開始打敗你正在做的事情的目的。如果您創建一個新類型,則必須轉換爲該類型。你也可以完全拋棄'Positive'類型,並明確檢查'func'中的負輸入。 –