• Umfasst alle Datentypen, für die es mapping gibt
  • Definition (standard prelude)
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  
  • map ist fmap, beschränkt auf Listen

fmap: Bedingungen

fmap: Infix Notation

> (^2) `fmap` [1,2,3]   
[1,4,9]  
  
> (^2) <$> [1,2,3]  
[1,4,9]