gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 14:30:45 25 4
gpt4 key购买 nike

我定义了以下数据类型:

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)

最佳答案

可悲的是,你不能那样做—— 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

并且为了转换一个 Probabilityfmappable PF我们必须“抬起”它
liftPF :: Probability a -> PF a
liftPF p = PF $ \mp -> PD (collect $ map (first mp) (mass p))

关于haskell - 如何在 Haskell 中向 Functor 实例声明添加类约束?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25345055/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com