这就是我想要做的:
data X = I Int | D Double deriving (Show, Eq, Ord)
{-
-- A normal declaration which works fine
instance Num X where
(I a) + (I b) = I $ a + b
(D a) + (D b) = D $ a + b
-- ...
-}
coerce :: Num a => X -> X -> (a -> a -> a) -> X
coerce (I a) (I b) op = I $ a `op` b
coerce (D a) (D b) op = D $ a `op` b
instance Num X where
a + b = coerce a b (+)
编译时出现错误:
tc.hs:18:29:
Couldn't match type `Double' with `Int'
In the second argument of `($)', namely `a `op` b'
In the expression: I $ a `op` b
In an equation for `coerce': coerce (I a) (I b) op = I $ a `op` b
在coerce
我想解释op
为Int -> Int -> Int
和Double -> Double -> Double
。我想我应该能够做到这一点,因为 op 是 type Num a => a -> a -> a
。
我的主要目标是抽象出功能 Num 子类中所需的重复:我更愿意像在未注释版本中那样编写它。