这就是我想要做的:
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是Num a => a -> a -> a类型的。
我的主要目标是在functioning子类中抽象出所需的重复:我更愿意像在未注释版本中那样编写它。
发布于 2012-11-23 12:42:13
您对强制的定义将op的类型限制为第一个定义为Int -> Int -> Int,第二个为Double -> Double -> Double。如果您真的想说op在for all Num类中是多态的,那么您应该使用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)https://stackoverflow.com/questions/13523023
复制相似问题