我正在尝试在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)
有什么想法吗?
答案 0 :(得分:2)
错误是由于未将Ord谓词分配给类型变量k。就这样做:
instance Ord k => Functor' (Map.Map k) where