Skip to content
Haskell

Functors, Applicatives, Monad Type Classes

The three core abstraction type classes.

By EZ4Code Team
functorapplicativemonad

Code

-- Functor: map over a structure
class Functor f where
  fmap :: (a -> b) -> f a -> f b

-- Maybe is a Functor
instance Functor Maybe where
  fmap _ Nothing = Nothing
  fmap f (Just x) = Just (f x)

fmap (+1) (Just 5)        -- Just 6
fmap (+1) Nothing         -- Nothing
fmap length (Just "hi")   -- Just 2

-- List is a Functor (fmap = map)
fmap (*2) [1,2,3]         -- [2,4,6]

-- Applicative: apply wrapped functions
class Functor f => Applicative f where
  pure :: a -> f a
  (<*>) :: f (a -> b) -> f a -> f b

-- Maybe is Applicative
pure (+) <*> Just 3 <*> Just 5  -- Just 8
pure (+) <*> Nothing <*> Just 5 -- Nothing

-- Monad: chain
class Applicative m => Monad m where
  (>>=) :: m a -> (a -> m b) -> m b
  return :: a -> m a   -- = pure

-- Usage
Just 3 >>= \x -> Just (x * 2)         -- Just 6
[1,2] >>= \x -> [x, x*10]            -- [1,10,2,20]

Explanation

Functor (fmap): transform inside a context. Applicative (<*>): apply wrapped functions to wrapped values — useful for multi-arg functions. Monad (>>=): chain dependent computations. These three form a hierarchy: every Monad is Applicative, every Applicative is Functor. Mastering them unlocks Haskell's expressiveness and library ecosystem (parsers, effects, streaming).

More Haskell Snippets