class Functor f where fmap :: (a -> b) -> f a -> f b
Beispiele
Für []
instance Functor [] where fmap = map
Für Maybe
instance Functor Maybe where fmap f (Just x) = Just (f x) fmap f Nothing = Nothing
Für Eigene Datentypen
data Tree a = Leaf a | Node (Tree a) (Tree a) instance Functor Tree where fmap g (Leaf x) = Leaf (g x) fmap g (Node l r) = Node (fmap g l) (fmap g r) > fmap length (Leaf "abc") Leaf 3> fmap even (Node (Leaf 1) (Leaf 2)) Node (Leaf False) (Leaf True)
fmap vs map
Vergleich der Signaturen von fmap und map
map :: (a -> b) -> [a] -> [b] fmap :: (a -> b) -> f a -> f b