我定义了类似“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
答案 0 :(得分:6)
由于PositiveInteger
现在是Num
的实例,10
(其最常见类型为Num a => a
)可以使用PositiveInteger
类型,因此fromPositiveInteger
的有效参数。