newtype:有人可以解释一下,这段代码是如何工作的?

时间:2016-04-23 17:30:41

标签: haskell

我定义了类似“PositiveInteger”的新类型,如下所示。

newtype PositiveInteger = PositiveInteger Integer deriving Show

fromPositiveInteger :: PositiveInteger -> Integer
fromPositiveInteger (PositiveInteger i) = i

toPositiveInteger :: Integer -> PositiveInteger
toPositiveInteger x
    | (x < 0) = error "Not applicable to negative numbers"
    | otherwise = PositiveInteger x

当我执行语句'fromPositiveInteger(10)'时,我收到以下错误。这绝对没问题。

*Main> fromPositiveInteger (10)

<interactive>:7:22:
    No instance for (Num PositiveInteger) arising from the literal ‘10’
    In the first argument of ‘fromPositiveInteger’, namely ‘(10)’
    In the expression: fromPositiveInteger (10)
    In an equation for ‘it’: it = fromPositiveInteger (10)

假设,如果我更新了我的代码,如下所示。 'fromPositiveInteger 10'语句没有任何错误。怎么会发生这种情况?

newtype PositiveInteger = PositiveInteger Integer deriving Show

fromPositiveInteger :: PositiveInteger -> Integer
fromPositiveInteger (PositiveInteger i) = i

toPositiveInteger :: Integer -> PositiveInteger
toPositiveInteger x
    | (x < 0) = error "Not applicable to negative numbers"
    | otherwise = PositiveInteger x

instance Num PositiveInteger where
    fromInteger         = toPositiveInteger
    x + y               = toPositiveInteger (fromPositiveInteger x + fromPositiveInteger y)
    x - y               = let r = fromPositiveInteger x - fromPositiveInteger y in
                            if r < 0 then error "Unnatural subtraction"
                                     else toPositiveInteger r
    x * y               = toPositiveInteger (fromPositiveInteger x * fromPositiveInteger y)

*Main> fromPositiveInteger (PositiveInteger 10)
10
*Main> fromPositiveInteger 10
10

1 个答案:

答案 0 :(得分:6)

由于PositiveInteger现在是Num的实例,10(其最常见类型为Num a => a)可以使用PositiveInteger类型,因此fromPositiveInteger的有效参数。