如何在Haskell中向Functor实例声明添加类约束?

时间:2014-08-16 23:47:11

标签: haskell

我定义了以下数据类型:

data Probability a = PD { mass :: [(a, Ratio Int)] } 

现在我想写一下Functor的实例:

collect :: (Eq a, Num b) => [(a, b)] -> [(a, b)]
collect al = map collect' keys where
    keys = nub $ map fst al
    collect' k = (k, sum (map snd (matches k)))
    matches k = filter ((==) k . fst) al

instance (Eq a) => Functor (Probability a) where
    fmap f p = PD (collect $ map (first f) (mass p))

但是,我收到以下错误:

Kind mis-match
The first argument of `Functor' should have kind `* -> *',
but `Probability a' has kind `*'
In the instance declaration for `Functor (Probability a)'

如何添加必要的Eq a约束? (我正在使用GHC 7.4.1)

2 个答案:

答案 0 :(得分:8)

可悲的是,你不能这样做 - Functor实例必须接受任何类型的映射函数而不受限制。

但你可以伪装它。

newtype PF a = PF { unPF :: forall r . Eq r => (a -> r) -> Probability r }

instance Functor PF where
  fmap f (PF p) = PF (\mp -> p (mp . f))

此处,Probability上映射的所有函数都已由PF“延迟”。我们通过在可能的情况下“降低”回Probability来一次性地运行它们

lowerPF :: Eq a => PF a -> Probability a
lowerPF pf = unPF pf id

为了将Probability转换为fmappable PF,我们必须“解除”它

liftPF :: Probability a -> PF a
liftPF p = PF $ \mp -> PD (collect $ map (first mp) (mass p))

答案 1 :(得分:4)

你写的不是一个仿函数。仿函数的fmap必须支持映射的任意值类型,而不仅仅是那些满足某个约束的值。您可以将其作为更一般概念的实例。例如,包constrained-categories定义了一类受约束的仿函数。