Show Menu
Cheatography

Haskell patterns Cheat Sheet by

Compos­ition and applic­ation

(.) ::­ (b­ ->­ c)­ ->­ (a­ ->­ b)­ ->­ ­a ->­ c
function compos­ition
($) ::­ (a­ ->­ b)­ ->­ a ­-> b
applic­ation operator, has low, right-­ass­oci­ative binding preced­ence, for example f $ g ­$ h­ x ­ = ­ f ­(g ­(h x))

Monoid

typeclass where empty/­append are defined
mempty­  :­: M­onoid a => a
identity of mappend (mappend mempty x = x)
mappend :: Monoid a => a -> a -> a
append two monoids (assoc­iative: brackets does not matter)
mappend x (mappend y z) = mappend (mappend x y) z
<> ­   ­  :­: M­onoid m => m -> m -> m
infix synonym for mappend ("­he" <> "­llo­")
mconcat :: [a] -> a
fold list using mappend and mempty

Functor

typeclass where fmap (map/<$>) is defined
should satisfy laws
fmap id == id
fmap (f . g) == fmap f . fmap g
fmap :: Functor f => (a -> b) -> f a -> f b
map function over functor
fmap (+1) (Just 3) is Just 4
<$>  :: Functor f => (a -> b) -> f a -> f b
function mapped over functor
infix synonym for fmap
(+1) <$> (Just 3) is Just 4

Applic­ative

typeclass where pure/<*> are defined
have Functor as super class

every instance of Applic­ative must have instance of Functor
so fmap (map/<$>) can be used
pure :: Applic­ative f => a -> f a
create an instance of Applicative
pure 3 :: [Int] is [3]
pure 3 :: Maybe Int is Just 3
pure (+3) :: Maybe (Int -> Int) is Just a function from Int to Int
pure (+3) :: [Int -> Int] is list of function
pure 1 :: IO Int is how it is printed in ghci
(<*­>) :: Applic­ative f => f (a -> b) -> f a -> f b
sequential applic­ation / apply
Just (+1) <*> Just 1 :: Maybe Int is Just 2
[(+1), (+2)] <*> [0] :: [Int] is [1, 2]

Monad

typeclass
have Applic­ative as super class

every instance of Monad must have instance of Applic­ative and Functor
so fmap (map/<$>) and <*>/pure can be used
return :: Monad m => a -> m a
is pure
(>>) :: Monad m => m a -> m b -> m b
sequen­tially compose two monads, first is usually
Just 2 >> Just 3 is Just 3
Nothing >> Just 3 is Nothing
[9, 9] >> [0, 0, 0] is [0,0,0­,0,0,0]
(>>=) :: Monad m => m a -> (a -> m b) -> m b
bind, sequen­tially compose two monads, value of first passed as argument to the second
Just 3 >>= \x -> Just (x + 1) is Just 4
Nothing >>= \x -> Just (x + 1) is Nothing
[0, 0] >>= \x -> [x + 1] is [1, 1]
[0, 0] >>= \x -> [x + 1, 2] is [1,2,1,2]
[] >>= \x -> [x + 1] is []
 

Comments

No comments yet. Add yours below!

Add a Comment

Your Comment

Please enter your name.

    Please enter your email address

      Please enter your Comment.

          Related Cheat Sheets

          GHC and RTS Options Cheat Sheet

          More Cheat Sheets by logcat