2

这就是我想要做的:

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我想解释opInt -> Int -> IntDouble -> Double -> Double。我想我应该能够做到这一点,因为 op 是 type Num a => a -> a -> a

我的主要目标是抽象出功能 Num 子类中所需的重复:我更愿意像在未注释版本中那样编写它。

4

1 回答 1

8

您对强制的定义将操作类型限制为Int -> Int -> Int第一个定义和Double -> Double -> Double第二个定义。如果您真的想说它op在 a for allNum类中是多态的,那么您应该使用Rank2Types它来使其工作。

coerce :: X -> X -> (forall a . Num a => a -> a -> a) -> X
coerce (I a) (I b) op = I $ a `op` b
coerce (D a) (D b) op = D $ a `op` b
coerce (I a) (D b) op = D $ op (fromIntegral a) b
coerce (D a) (I b) op = D $ op a (fromIntegral b)
于 2012-11-23T04:42:13.123 回答