5

我正在尝试通过 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)

有任何想法吗?

4

1 回答 1

2

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

instance Ord k => Functor' (Map.Map k) where
于 2012-06-29T03:17:00.133 回答