Skip to content
Haskell

Functors, Applicatives, Type Classes Monad

As três type classes de abstração central.

#functor#applicative#monad

Code

haskell
-- 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]