gpt4 book ai didi

haskell - "No instance for (Ord k)"在 Data.Map.Map 上实现 Functor 时

转载 作者:行者123 更新时间:2023-12-04 15:46:45 24 4
gpt4 key购买 nike

我正在尝试通过 Data.Map.Map 实现 Functor fmap,但出现错误。我确定我不需要在 Map 和 List 之间来回转换才能使其正常工作,但这是迄今为止我想出的最好的。

class Functor' f where
fmap' :: (a -> b) -> f a -> f b

instance Functor' (Map.Map k) where
fmap' f m
| Map.null m = Map.empty
| otherwise = let x:xs = Map.toList m
mtail = Map.fromList xs
a = fst x
b = snd x
in Map.insert a (f b) (fmap f mtail)

错误:
No instance for (Ord k)
arising from a use of `Map.fromList'
In the expression: Map.fromList xs
In an equation for `mtail': mtail = Map.fromList xs
In the expression:
let
x : xs = Map.toList m
mtail = Map.fromList xs
a = fst x
....
in Map.insert a (f b) (fmap f mtail)

有任何想法吗?

最佳答案

错误是由于没有将 Ord 谓词分配给类型变量 k。只需这样做:

instance Ord k => Functor' (Map.Map k) where

关于haskell - "No instance for (Ord k)"在 Data.Map.Map 上实现 Functor 时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11255436/

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