"在Data.Map.Map上实现Functor时没有(Ord k)的实例"

pyr*_*ade 6 haskell functional-programming tail-recursion functor

我试图在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)
Run Code Online (Sandbox Code Playgroud)

错误:

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)
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

小智 2

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

instance Ord k => Functor' (Map.Map k) where
Run Code Online (Sandbox Code Playgroud)