避免重复实例和代码重复

时间:2014-02-17 19:51:57

标签: haskell typeclass

假设我有一个类型类Convertable

{-# LANGUAGE MultiParamTypeClasses, FlexibleInstances #-}

class Convertable a b where
    convert :: a -> b

首先,将一种类型转换为同一类型是身份:

instance Convertable a a where
    convert = id

假设我们想要在整数和浮点数之间进行转换:

instance Convertable Int Float where
    convert = fromIntegral

instance Convertable Float Int where
    convert = round

到目前为止,这么好。但我想概括一下这包括所有积分典型和所有RealFracs:

instance (Integral a, RealFrac b) => Convertable a b where
    convert = fromIntegral

instance (RealFrac a, Integral b) => Convertable a b where
    convert = round

GHC不喜欢这样:

  Duplicate instance declarations:
    instance (Integral a, RealFrac b) => Convertable a b
      -- Defined at test.hs:9:10
    instance (RealFrac a, Integral b) => Convertable a b
      -- Defined at test.hs:12:10

这有什么好的解决方案可以节省我创建m x n个实例吗?

0 个答案:

没有答案