Haskell只允许正输入

时间:2014-05-01 14:02:01

标签: haskell

我需要定义一个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>

1 个答案:

答案 0 :(得分:2)

您忘记致电toPositiveInt转换为Positive。这样称呼:

func $ toPositive 1

另外,Haskell的一个怪癖是处理负数文字。为避免与减法运算符混淆,必须将它们括在括号中:

func $ toPositive (-1)