SlideShare a Scribd company logo
Functors,
Applicatives,
Monads
Motivation
Functors, Applicatives, Monads
● Why Oh Why?
● I am going back to PHP
● Gimme my imperative code back
● Let me get my PhD first
Why should I bother?
7 ± 2
The Magical Number Seven, Plus or Minus Two - George Miller
Surface Area vs Volume
Functions vs Subroutines
int square(int n)
square :: Int -> Int
Functions vs Subroutines
● Totality
● Determinism
● Purity
● Parameters
● Results
● Composition
Function Composition
● Build larger programs by composing smaller functions together
xs = [1, 2, 3, 4, 5]
stddev xs = sqrt . average . map (square . (mu -)) xs
pyth x y = sqrt (square x + square y)
● How does values flow from function to function?
Functions vs Subroutines
But real world programs are not like this.
1. Null handling
2. Exceptions
3. Logging
4. IO
● Simple function composition breaks down in these cases
Example
replaceDotsInKeys :: Value -> Value
replaceDotsInKeys = ...
filterSecret :: Value -> Value
filterSecret = ...
processValue :: Value -> Value
processValue = replaceDotsInKeys . filterSecret
Logger
newtype Logger l a = Logger (a, l)
log :: l -> Logger l ()
log l = Logger ((), l)
● But how do I use my existing functions with Logger?
filterSecret' :: Logger l Value -> Logger l Value
replaceDotsInKeys' :: Logger l Value -> Logger l Value
filterSecret' (Logger (x, l)) = Logger (filterSecret x, l)
● What’s the problem with this?
Logger
liftLogger :: (a -> b) -> Logger l a -> Logger l b
liftLogger f (Logger (x, l)) = Logger (f x, l)
replaceDotsInKeys' :: Logger l Value -> Logger l Value
replaceDotsInKeys' = liftLogger replaceDotsInKeys
Maybe
data Maybe a = Just a | Nothing
● But how do I use my existing functions with Maybe?
filterSecret' :: Maybe Value -> Maybe Value
replaceDotsInKeys' :: Maybe Value -> Maybe Value
filterSecret' (Just x) = Just (filterSecret x)
filterSecret' Nothing = Nothing
● What’s the problem with this?
Maybe
liftMaybe :: (a -> b) -> Maybe a -> Maybe b
liftMaybe f (Just x) = Just (f x)
liftMaybe f Nothing = Nothing
replaceDotsInKeys' :: Maybe Value -> Maybe Value
replaceDotsInKeys' = liftMaybe replaceDotsInKeys
Functors
class Functor f where
fmap :: (a -> b) -> f a -> f b
instance Functor (Logger l) where
fmap f (Logger (x, l)) = Logger (f x, l)
instance Functor Maybe where
fmap f (Just x) = Just (f x)
fmap f Nothing = Nothing
Functors
processValue' :: Logger l Value -> Logger l Value
processValue' = fmap (replaceDotsInKeys . filterSecret)
processValue' :: Maybe Value -> Maybe Value
processValue' = fmap (replaceDotsInKeys . filterSecret)
processValue' :: Functor f => f Value -> f Value
processValue' = fmap (replaceDotsInKeys . filterSecret)
Functions with multiple arguments
fmap :: (a -> b) -> Logger l a -> Logger l b
(+) :: (Int -> (Int -> Int))
x :: Logger l Int
y :: Logger l Int
fmap (+) x :: Logger l (Int -> Int)
fmap (+) x y :: ???
● We need something that can do
Logger l (a -> b) -> Logger l a -> Logger l b
Applicative
class Functor f => Applicative f where
pure :: a -> f a
(<*>) :: f (a -> b) -> f a -> f b
instance Monoid l => Applicative (Logger l) where
pure x = Logger (x, mempty)
Logger (f, l) <*> Logger (x, l') = Logger (f x, l `mappend` l')
Applicative
(fmap (+) (pure 1)) <*> (pure 2) = pure 3
(+) <$> (pure 1) <*> (pure 2) = pure 3
((+) $ 1) $ 2 = 3
f <$> (pure x) <*> (pure y) <*> (pure z) = pure (f x y z)
f <$> (g x) <*> (h y) = do { a <- g x; b <- h y; pure (f a b) }
I want more!
Double f(String name)
{
Double val = hashmap.lookup(name);
Double result = sqrt(val);
log(....);
return result;
}
Contextual Computation
lookup :: String -> Logger l Double
sqrt :: Double -> Logger l Double
f :: String -> Logger l Double
● We are back to our composition problem
Contextual Computation
f name = lookup name `bind` sqrt
bind :: Monoid l => Logger l a -> (a -> Logger l b) -> Logger l b
bind (Logger (x, l)) f = let Logger (y, l') = f x
in Logger (y, l `mappend` l')
Monads
class Applicative m => Monad m where
return :: a -> m a
(>>=) :: m a -> (a -> m b) -> m b
instance Monoid l => Monad (Logger l) where
return = pure
Logger (x, l) >>= f = let Logger (y, l') = f x
in Logger (y, l `mappend` l')
Comparison
fmap :: (a -> b) -> m a -> m b
<*> :: m (a -> b) -> m a -> m b
=<< :: (a -> mb) -> m a -> m b
● How do these compare with each other?

More Related Content

PDF
Composition in JavaScript
PDF
Javascript & Ajax Basics
PDF
삼성 바다 앱개발 실패 노하우 2부
PDF
A taste of Functional Programming
PDF
C++ ARRAY WITH EXAMPLES
PDF
Fun with functions
PDF
Free Monads Getting Started
Composition in JavaScript
Javascript & Ajax Basics
삼성 바다 앱개발 실패 노하우 2부
A taste of Functional Programming
C++ ARRAY WITH EXAMPLES
Fun with functions
Free Monads Getting Started

What's hot (20)

PDF
A "Do-It-Yourself" Specification Language with BeepBeep 3 (Talk @ Dagstuhl 2017)
PDF
MP in Clojure
PDF
アプリカティブファンクターとHaskell 2014版
PDF
Swift 3.0 で変わったところ - 厳選 13 項目 #love_swift #cswift
PPTX
simple linear regression
PPT
Python легко и просто. Красиво решаем повседневные задачи
PPT
Cpp tutorial
PPTX
random forest regression
PPTX
20170714 concurrency in julia
PPT
Operator Overloading
PDF
Introduction to functional programming using Ocaml
PPTX
20170317 functional programming in julia
PPTX
Queue oop
PDF
Stl algorithm-Basic types
PDF
All I know about rsc.io/c2go
PDF
Data structure lab manual
PDF
[JuraSIC! Meetup] Mateusz Stasch - Monady w .NET
PDF
Swift - Krzysztof Skarupa
PDF
The best of AltJava is Xtend
A "Do-It-Yourself" Specification Language with BeepBeep 3 (Talk @ Dagstuhl 2017)
MP in Clojure
アプリカティブファンクターとHaskell 2014版
Swift 3.0 で変わったところ - 厳選 13 項目 #love_swift #cswift
simple linear regression
Python легко и просто. Красиво решаем повседневные задачи
Cpp tutorial
random forest regression
20170714 concurrency in julia
Operator Overloading
Introduction to functional programming using Ocaml
20170317 functional programming in julia
Queue oop
Stl algorithm-Basic types
All I know about rsc.io/c2go
Data structure lab manual
[JuraSIC! Meetup] Mateusz Stasch - Monady w .NET
Swift - Krzysztof Skarupa
The best of AltJava is Xtend
Ad

Similar to Functors, applicatives, monads (20)

PDF
Functional programming with haskell
PDF
08. haskell Functions
PDF
Functional python
PDF
10. haskell Modules
PDF
09. haskell Context
PDF
Introduction to Functional Programming
PDF
Functional programming ii
PDF
Why Haskell Matters
PDF
Functional Programming Patterns (NDC London 2014)
PDF
Java 8 lambda expressions
PPT
Introduction to Functional Programming in JavaScript
PDF
Monads in Swift
PDF
TI1220 Lecture 6: First-class Functions
PPTX
ZIO: Powerful and Principled Functional Programming in Scala
PPTX
python ppt.pptx
PDF
Humble introduction to category theory in haskell
PDF
Functional Programming Patterns (BuildStuff '14)
PDF
Composition birds-and-recursion
PPTX
Столпы функционального программирования для адептов ООП, Николай Мозговой
PDF
Functional programming from its fundamentals
Functional programming with haskell
08. haskell Functions
Functional python
10. haskell Modules
09. haskell Context
Introduction to Functional Programming
Functional programming ii
Why Haskell Matters
Functional Programming Patterns (NDC London 2014)
Java 8 lambda expressions
Introduction to Functional Programming in JavaScript
Monads in Swift
TI1220 Lecture 6: First-class Functions
ZIO: Powerful and Principled Functional Programming in Scala
python ppt.pptx
Humble introduction to category theory in haskell
Functional Programming Patterns (BuildStuff '14)
Composition birds-and-recursion
Столпы функционального программирования для адептов ООП, Николай Мозговой
Functional programming from its fundamentals
Ad

Recently uploaded (20)

PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
KodekX | Application Modernization Development
PDF
NewMind AI Monthly Chronicles - July 2025
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PPTX
MYSQL Presentation for SQL database connectivity
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
Empathic Computing: Creating Shared Understanding
PPTX
A Presentation on Artificial Intelligence
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
Review of recent advances in non-invasive hemoglobin estimation
PPTX
Cloud computing and distributed systems.
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
NewMind AI Weekly Chronicles - August'25 Week I
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
KodekX | Application Modernization Development
NewMind AI Monthly Chronicles - July 2025
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Understanding_Digital_Forensics_Presentation.pptx
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Advanced methodologies resolving dimensionality complications for autism neur...
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Diabetes mellitus diagnosis method based random forest with bat algorithm
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
MYSQL Presentation for SQL database connectivity
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Empathic Computing: Creating Shared Understanding
A Presentation on Artificial Intelligence
Encapsulation_ Review paper, used for researhc scholars
Review of recent advances in non-invasive hemoglobin estimation
Cloud computing and distributed systems.
Digital-Transformation-Roadmap-for-Companies.pptx

Functors, applicatives, monads

  • 2. Functors, Applicatives, Monads ● Why Oh Why? ● I am going back to PHP ● Gimme my imperative code back ● Let me get my PhD first
  • 3. Why should I bother? 7 ± 2 The Magical Number Seven, Plus or Minus Two - George Miller Surface Area vs Volume
  • 4. Functions vs Subroutines int square(int n) square :: Int -> Int
  • 5. Functions vs Subroutines ● Totality ● Determinism ● Purity ● Parameters ● Results ● Composition
  • 6. Function Composition ● Build larger programs by composing smaller functions together xs = [1, 2, 3, 4, 5] stddev xs = sqrt . average . map (square . (mu -)) xs pyth x y = sqrt (square x + square y) ● How does values flow from function to function?
  • 7. Functions vs Subroutines But real world programs are not like this. 1. Null handling 2. Exceptions 3. Logging 4. IO ● Simple function composition breaks down in these cases
  • 8. Example replaceDotsInKeys :: Value -> Value replaceDotsInKeys = ... filterSecret :: Value -> Value filterSecret = ... processValue :: Value -> Value processValue = replaceDotsInKeys . filterSecret
  • 9. Logger newtype Logger l a = Logger (a, l) log :: l -> Logger l () log l = Logger ((), l) ● But how do I use my existing functions with Logger? filterSecret' :: Logger l Value -> Logger l Value replaceDotsInKeys' :: Logger l Value -> Logger l Value filterSecret' (Logger (x, l)) = Logger (filterSecret x, l) ● What’s the problem with this?
  • 10. Logger liftLogger :: (a -> b) -> Logger l a -> Logger l b liftLogger f (Logger (x, l)) = Logger (f x, l) replaceDotsInKeys' :: Logger l Value -> Logger l Value replaceDotsInKeys' = liftLogger replaceDotsInKeys
  • 11. Maybe data Maybe a = Just a | Nothing ● But how do I use my existing functions with Maybe? filterSecret' :: Maybe Value -> Maybe Value replaceDotsInKeys' :: Maybe Value -> Maybe Value filterSecret' (Just x) = Just (filterSecret x) filterSecret' Nothing = Nothing ● What’s the problem with this?
  • 12. Maybe liftMaybe :: (a -> b) -> Maybe a -> Maybe b liftMaybe f (Just x) = Just (f x) liftMaybe f Nothing = Nothing replaceDotsInKeys' :: Maybe Value -> Maybe Value replaceDotsInKeys' = liftMaybe replaceDotsInKeys
  • 13. Functors class Functor f where fmap :: (a -> b) -> f a -> f b instance Functor (Logger l) where fmap f (Logger (x, l)) = Logger (f x, l) instance Functor Maybe where fmap f (Just x) = Just (f x) fmap f Nothing = Nothing
  • 14. Functors processValue' :: Logger l Value -> Logger l Value processValue' = fmap (replaceDotsInKeys . filterSecret) processValue' :: Maybe Value -> Maybe Value processValue' = fmap (replaceDotsInKeys . filterSecret) processValue' :: Functor f => f Value -> f Value processValue' = fmap (replaceDotsInKeys . filterSecret)
  • 15. Functions with multiple arguments fmap :: (a -> b) -> Logger l a -> Logger l b (+) :: (Int -> (Int -> Int)) x :: Logger l Int y :: Logger l Int fmap (+) x :: Logger l (Int -> Int) fmap (+) x y :: ??? ● We need something that can do Logger l (a -> b) -> Logger l a -> Logger l b
  • 16. Applicative class Functor f => Applicative f where pure :: a -> f a (<*>) :: f (a -> b) -> f a -> f b instance Monoid l => Applicative (Logger l) where pure x = Logger (x, mempty) Logger (f, l) <*> Logger (x, l') = Logger (f x, l `mappend` l')
  • 17. Applicative (fmap (+) (pure 1)) <*> (pure 2) = pure 3 (+) <$> (pure 1) <*> (pure 2) = pure 3 ((+) $ 1) $ 2 = 3 f <$> (pure x) <*> (pure y) <*> (pure z) = pure (f x y z) f <$> (g x) <*> (h y) = do { a <- g x; b <- h y; pure (f a b) }
  • 18. I want more! Double f(String name) { Double val = hashmap.lookup(name); Double result = sqrt(val); log(....); return result; }
  • 19. Contextual Computation lookup :: String -> Logger l Double sqrt :: Double -> Logger l Double f :: String -> Logger l Double ● We are back to our composition problem
  • 20. Contextual Computation f name = lookup name `bind` sqrt bind :: Monoid l => Logger l a -> (a -> Logger l b) -> Logger l b bind (Logger (x, l)) f = let Logger (y, l') = f x in Logger (y, l `mappend` l')
  • 21. Monads class Applicative m => Monad m where return :: a -> m a (>>=) :: m a -> (a -> m b) -> m b instance Monoid l => Monad (Logger l) where return = pure Logger (x, l) >>= f = let Logger (y, l') = f x in Logger (y, l `mappend` l')
  • 22. Comparison fmap :: (a -> b) -> m a -> m b <*> :: m (a -> b) -> m a -> m b =<< :: (a -> mb) -> m a -> m b ● How do these compare with each other?

Editor's Notes

  • #6: Totality. A function must yield a value for every possible input. Determinism. A function must yield the same value for the same input. Purity. A function’s only effect must be the computation of its return value. Composition is the key to deal with 7+-2 problem.