SlideShare a Scribd company logo
EFFECTING PURE CHANGE
HOW ANYTHING EVER GETS DONE IN FP
ANUPAM JAIN
2
Hello!
3
❑ MEETUP: https://www.meetup.com/DelhiNCR-Haskell-And-
Functional-Programming-Languages-Group
❑ TELEGRAM: https://t.me/fpncr
❑ GITHUB: https://github.com/fpncr
❑ SLACK: https://functionalprogramming.slack.com #FPNCR
FPNCR
4
Effects
5
❑ Programming with Mathematical Functions.
❑ A Function has Input and Output.
❑ Referentially Transparent
❑ A complete Program is just a function!
Functional Programming
6
❑ No Global State
❑ No Assignments
❑ No Statements
❑ No Input-Output
Referential Transparency
7
❑ Easier to Reason About
❑ Easier to Optimize
❑ Easier to Parallelize
❑ Easier to Test
❑ ???
Why?
8
SideEffects!!
9
What Happens If we
Ignore the Danger
10
write :: String -> ()
read :: () -> String
What could go wrong
11
write "Do you want a pizza?"
if (read() == "Yes") orderPizza()
write "Should I launch missiles?"
if (read() == "Yes") launchMissiles()
What could go wrong
PSEUDO-CODE
12
write "Do you want a pizza?"
if (read() == "Yes") orderPizza()
write "Should I launch missiles?"
if (read() == "Yes") launchMissiles()
What could go wrong
May be optimized away
13
write "Do you want a pizza?"
if (read() == "Yes") orderPizza()
write "Should I launch missiles?"
if (read() == "Yes") launchMissiles()
What could go wrong
May reuse value from
previous read()
14
OCAML
let val ha = (print "ha") in ha; ha end
HASKELL
let ha = putStr “ha” in ha >> ha
Referential Transparency is Vital
ha
haha
15
Taming Side Effects
16
❑ Separate “Effects” from “Values”
(Hint: Strong Types are great for this)
❑ Effects are forever. No way to recover a “pure” Value.
❑ As much as possible, tag the flavor of side effects. “Print”
cannot launch nukes.
Contain. Not Prohibit.
17
Effectful Logic
Pure Logic
Outside World
18
❑ React – Functional Views
❑ The Elm Architecture
❑ Functional Reactive Programming
❑ Monads and Algebraic Effects
Examples
19
render() {
let n = this.state.count
return <button onClick = {setState({count:n+1})}>{n}</button>
}
React – Functional Views
20
view address model =
button [onClick address Increment] [text (toString model)]
update action model = case action of
Increment -> model + 1
The Elm Architecture
21
❑ Interface between things that are static and those that vary
❑ Forms a graph of relationships between varying things
❑ The program creates the graph, and then lets things run. Akin
to cellular automata.
Functional Reactive
Programming
22
❑ Event a – e.g. Button Clicks
❑ Behaviour a – e.g. System Time
❑ toBehaviour :: Event a -> Behaviour a
❑ mergeEvents :: Event a -> Event a -> Event a
❑ zipBehaviour :: (a -> b -> c) -> Behaviour a -> Behaviour b ->
Behaviour c
FRP Primitives
23
❑ Event a – e.g. Button Clicks
❑ Behaviour a – e.g. System Time
❑ hold :: Event a -> Behaviour a
❑ sample :: Behaviour a -> Event b -> Event (a,b)
❑ merge :: Event a -> Event a -> Event a
❑ zip :: Behaviour a -> Behaviour b -> Behaviour (a,b)
FRP Primitives
24
❑ text :: Behaviour String -> IO ()
❑ button :: Event ()
❑ gui = do
clicks <- button
text hold “Not Clicked” (map (_ -> “Clicked!”) clicks)
FRP GUIs
25
Monads
26
❑ Tagged values
❑ Provide explicit control over sequencing
Monads
IO String
27
❑ Values can be evaluated in any order (or left unevaluated).
❑ Effects need explicit control over sequencing and sharing.
❑ The only way sequencing is possible in FP is through nested
functions. i.e. Callbacks.
Controlling Sequencing
write "Hello" (() -> write "World")
28
write "Do you want a pizza?" (
() -> read (
ans -> if (ans == "Yes") orderPizza (
() -> write "Should I launch missiles?" (
() -> read (
ans -> if (ans == "Yes") launchNukes () ) ) ) ) )
Continuation Passing Style
29
x <- foo
…
Sprinkle Some Syntactic Sugar
foo (x -> …)
30
() <- write "Do you want a pizza?“
ans <- read
if(ans == "Yes") () <- orderPizza
() <- write "Should I launch missiles?“
ans <- read
if (ans == "Yes") () <- launchNukes
Sprinkle Some Syntactic Sugar
write "Do you want a pizza?" (() ->
read (ans ->
if (ans == "Yes") orderPizza (() ->
write "Should I launch missiles?" (() ->
read (ans ->
if (ans == "Yes") launchNukes () ) ) ) ) )
31
do write "Do you want a pizza?“
ans <- read
if(ans == "Yes") orderPizza
write "Should I launch missiles?“
ans <- read
if (ans == "Yes") launchNukes
Do notation
32
❑ Callbacks are generally associated with Asynchronous code
❑ Do notation avoids “Callback Hell”
Asynchronous
Computations are Effects
ajax GET “google.com" (response -> …)
33
do
post <- ajax GET “/post/1“
map post.comments (cid -> do
comment <- ajax GET “/comments/{cid}“
…
)
Avoiding Callback Hell
ajax GET “/post/1" (post ->
map post.comments (cid ->
ajax GET “/comments/{cid}" (comment ->
…
) ) )
34
if(ans == "Yes") orderPizza
else ???
Where is the Else block?
35
if(ans == "Yes") orderPizza
else return ()
Where is the Else block?
36
Type: IO a
Bind: IO a -> (a -> IO b) -> IO b
Return: a -> IO a
The Monad
37
❑ Reader
❑ Logger
❑ State
❑ Exceptions
❑ Random
❑ …
Bring Your Own Monad
38
Type: Reader e a :: e -> a
Bind: Reader e a -> (a -> Reader e b) -> Reader e b
Return: a -> Reader e a
ask: Reader e e
runReader: e -> Reader e a -> a
Reader Monad
39
main = runReader myConfig do
res <- foo
bar res
foo = do config <- ask; …
bar res = do config <- ask; …
Reader Monad
40
“Haskell” is the world’s finest
imperative programming
language.
~Simon Peyton Jones
41
“Haskell” is the world’s finest
imperative programming
language.
~Simon Peyton Jones
(Creator of Haskell)
42
❑ Like Monads, you can define your own Effects
❑ But you can define the usage and handling of the effects
separately
❑ And effects compose freely (pun intended)
Algebraic Effects
43
data Console callback
= Read (String -> callback)
| Write String callback
handle (Read cb) = …
handle (Write s cb) = …
Console Effect PSEUDO-CODE
44
data Console callback
= Read (String -> callback)
| Write String callback
handle (Read cb) = s = do readLine(); cb(s)
handle (Write s cb) = do console.log(s); cb()
Console Effect PSEUDO-CODE
45
handle (Write s cb) = do console.log(s); console.log(s); cb();
handle (Write s cb) = cb();
handle (Write s cb) = do cb(); console.log(s);
handle (Write s cb) = do if(test(s)) console.log(s); cb();
You can do more things
PSEUDO-CODE
46
handle (Return x) = return (x,””);
handle (Write s cb) = (x,rest) = do cb(); return (x, s:rest);
Returning Values from
Handlers PSEUDO-CODE
47
SideEffects!!
48
BestFriends!!
49
Thank You

More Related Content

What's hot (20)

PDF
Go Concurrency
jgrahamc
 
PDF
Sistemas operacionais 13
Nauber Gois
 
DOCX
Tugas Program C++
Reynes E. Tekay
 
PDF
Taking Inspiration From The Functional World
Piotr Solnica
 
DOCX
serverstats
Ben De Koster
 
PDF
Javascript - The basics
Bruno Paulino
 
PPTX
Load-time Hacking using LD_PRELOAD
Dharmalingam Ganesan
 
PDF
함수형사고 4장 열심히보다는현명하게
박 민규
 
PDF
Basics
Logan Campbell
 
PDF
Are we ready to Go?
Adam Dudczak
 
TXT
Xstartup
Ahmed Abdelazim
 
PDF
Scroll pHAT HD に美咲フォント
Yuriko IKEDA
 
PDF
TrackPad Destroyer
PubNub
 
PPTX
Perl: Coro asynchronous
Shmuel Fomberg
 
PPTX
Arduino programming 101
visual28
 
ODP
UTAU DLL voicebank and ulauncher
hunyosi
 
PDF
Beware sharp tools
AgileOnTheBeach
 
PDF
Combine vs RxSwift
shark-sea
 
PDF
tensorflow/keras model coding tutorial 勉強会
RyoyaKatafuchi
 
PDF
R/C++ talk at earl 2014
Romain Francois
 
Go Concurrency
jgrahamc
 
Sistemas operacionais 13
Nauber Gois
 
Tugas Program C++
Reynes E. Tekay
 
Taking Inspiration From The Functional World
Piotr Solnica
 
serverstats
Ben De Koster
 
Javascript - The basics
Bruno Paulino
 
Load-time Hacking using LD_PRELOAD
Dharmalingam Ganesan
 
함수형사고 4장 열심히보다는현명하게
박 민규
 
Are we ready to Go?
Adam Dudczak
 
Xstartup
Ahmed Abdelazim
 
Scroll pHAT HD に美咲フォント
Yuriko IKEDA
 
TrackPad Destroyer
PubNub
 
Perl: Coro asynchronous
Shmuel Fomberg
 
Arduino programming 101
visual28
 
UTAU DLL voicebank and ulauncher
hunyosi
 
Beware sharp tools
AgileOnTheBeach
 
Combine vs RxSwift
shark-sea
 
tensorflow/keras model coding tutorial 勉強会
RyoyaKatafuchi
 
R/C++ talk at earl 2014
Romain Francois
 

Similar to Effecting Pure Change - How anything ever gets done in functional programming languages - Anupam Jain (S&P Global) (20)

PPTX
Programming python quick intro for schools
Dan Bowen
 
PDF
Introdução à Spring Web Flux
Wellington Gustavo Macedo
 
PPTX
Async fun
💡 Tomasz Kogut
 
PDF
Supercharged imperative programming with Haskell and Functional Programming
Tech Triveni
 
PDF
Hierarchical free monads and software design in fp
Alexander Granin
 
DOCX
Design problem
Sanjay Kumar Chakravarti
 
PDF
InterConnect: Server Side Swift for Java Developers
Chris Bailey
 
PDF
Functional Reactive Programming / Compositional Event Systems
Leonardo Borges
 
PDF
Python Menu
cfministries
 
PPTX
ZIO: Powerful and Principled Functional Programming in Scala
Wiem Zine Elabidine
 
PPTX
Segmentation Faults, Page Faults, Processes, Threads, and Tasks
David Evans
 
PDF
Mining event streams with BeepBeep 3
Sylvain Hallé
 
PPTX
Introduction to java Programming
Ahmed Ayman
 
PDF
Writing Faster Python 3
Sebastian Witowski
 
PDF
datastructure-1 lab manual journals practical
AlameluIyer3
 
PDF
Monadologie
league
 
PDF
‘How to develop Pythonic coding rather than Python coding – Logic Perspective’
S.Mohideen Badhusha
 
PDF
Subtle Asynchrony by Jeff Hammond
Patrick Diehl
 
PDF
How fast ist it really? Benchmarking in practice
Tobias Pfeiffer
 
PPS
CS101- Introduction to Computing- Lecture 35
Bilal Ahmed
 
Programming python quick intro for schools
Dan Bowen
 
Introdução à Spring Web Flux
Wellington Gustavo Macedo
 
Supercharged imperative programming with Haskell and Functional Programming
Tech Triveni
 
Hierarchical free monads and software design in fp
Alexander Granin
 
Design problem
Sanjay Kumar Chakravarti
 
InterConnect: Server Side Swift for Java Developers
Chris Bailey
 
Functional Reactive Programming / Compositional Event Systems
Leonardo Borges
 
Python Menu
cfministries
 
ZIO: Powerful and Principled Functional Programming in Scala
Wiem Zine Elabidine
 
Segmentation Faults, Page Faults, Processes, Threads, and Tasks
David Evans
 
Mining event streams with BeepBeep 3
Sylvain Hallé
 
Introduction to java Programming
Ahmed Ayman
 
Writing Faster Python 3
Sebastian Witowski
 
datastructure-1 lab manual journals practical
AlameluIyer3
 
Monadologie
league
 
‘How to develop Pythonic coding rather than Python coding – Logic Perspective’
S.Mohideen Badhusha
 
Subtle Asynchrony by Jeff Hammond
Patrick Diehl
 
How fast ist it really? Benchmarking in practice
Tobias Pfeiffer
 
CS101- Introduction to Computing- Lecture 35
Bilal Ahmed
 
Ad

More from Tech Triveni (20)

PDF
UI Dev in Big data world using open source
Tech Triveni
 
PDF
Why should a Java programmer shifts towards Functional Programming Paradigm
Tech Triveni
 
PDF
Reactive - Is it really a Magic Pill?
Tech Triveni
 
PDF
Let’s go reactive with JAVA
Tech Triveni
 
PDF
Tackling Asynchrony with Kotlin Coroutines
Tech Triveni
 
PDF
Programmatic Ad Tracking: Let the power of Reactive Microservices do talking
Tech Triveni
 
PDF
Let's refine your Scala Code
Tech Triveni
 
PDF
Observability at scale with Neural Networks: A more proactive approach
Tech Triveni
 
PDF
Semi-Supervised Insight Generation from Petabyte Scale Text Data
Tech Triveni
 
PDF
Finding the best solution for Image Processing
Tech Triveni
 
PDF
Proximity Targeting at Scale using Big Data Platforms
Tech Triveni
 
PDF
Becoming a Functional Programmer - Harit Himanshu (Nomis Solutions)
Tech Triveni
 
PDF
Live coding session on AI / ML using Google Tensorflow (Python) - Tanmoy Deb ...
Tech Triveni
 
PDF
Distributing the SMACK stack - Kubernetes VS DCOS - Sahil Sawhney (Knoldus Inc.)
Tech Triveni
 
PDF
Blue Pill / Red Pill : The Matrix of thousands of data streams - Himanshu Gup...
Tech Triveni
 
PDF
UX in Big Data Analytics - Paramjit Jolly (Guavus)
Tech Triveni
 
PDF
Simplified Scala Monads And Transformation - Harmeet Singh (Knoldus Inc.)
Tech Triveni
 
PDF
Micro Frontends Architecture - Jitendra kumawat (Guavus)
Tech Triveni
 
PDF
Apache CarbonData+Spark to realize data convergence and Unified high performa...
Tech Triveni
 
PPTX
Micro Frontends Architecture - Jitendra kumawat (Guavus)
Tech Triveni
 
UI Dev in Big data world using open source
Tech Triveni
 
Why should a Java programmer shifts towards Functional Programming Paradigm
Tech Triveni
 
Reactive - Is it really a Magic Pill?
Tech Triveni
 
Let’s go reactive with JAVA
Tech Triveni
 
Tackling Asynchrony with Kotlin Coroutines
Tech Triveni
 
Programmatic Ad Tracking: Let the power of Reactive Microservices do talking
Tech Triveni
 
Let's refine your Scala Code
Tech Triveni
 
Observability at scale with Neural Networks: A more proactive approach
Tech Triveni
 
Semi-Supervised Insight Generation from Petabyte Scale Text Data
Tech Triveni
 
Finding the best solution for Image Processing
Tech Triveni
 
Proximity Targeting at Scale using Big Data Platforms
Tech Triveni
 
Becoming a Functional Programmer - Harit Himanshu (Nomis Solutions)
Tech Triveni
 
Live coding session on AI / ML using Google Tensorflow (Python) - Tanmoy Deb ...
Tech Triveni
 
Distributing the SMACK stack - Kubernetes VS DCOS - Sahil Sawhney (Knoldus Inc.)
Tech Triveni
 
Blue Pill / Red Pill : The Matrix of thousands of data streams - Himanshu Gup...
Tech Triveni
 
UX in Big Data Analytics - Paramjit Jolly (Guavus)
Tech Triveni
 
Simplified Scala Monads And Transformation - Harmeet Singh (Knoldus Inc.)
Tech Triveni
 
Micro Frontends Architecture - Jitendra kumawat (Guavus)
Tech Triveni
 
Apache CarbonData+Spark to realize data convergence and Unified high performa...
Tech Triveni
 
Micro Frontends Architecture - Jitendra kumawat (Guavus)
Tech Triveni
 
Ad

Recently uploaded (20)

PPTX
OpenID AuthZEN - Analyst Briefing July 2025
David Brossard
 
PPTX
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 
PPTX
Building Search Using OpenSearch: Limitations and Workarounds
Sease
 
PPTX
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
PDF
Presentation - Vibe Coding The Future of Tech
yanuarsinggih1
 
PDF
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
PDF
Empower Inclusion Through Accessible Java Applications
Ana-Maria Mihalceanu
 
PDF
DevBcn - Building 10x Organizations Using Modern Productivity Metrics
Justin Reock
 
PDF
HCIP-Data Center Facility Deployment V2.0 Training Material (Without Remarks ...
mcastillo49
 
PDF
Fl Studio 24.2.2 Build 4597 Crack for Windows Free Download 2025
faizk77g
 
PDF
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PDF
NewMind AI - Journal 100 Insights After The 100th Issue
NewMind AI
 
PDF
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
PDF
Using FME to Develop Self-Service CAD Applications for a Major UK Police Force
Safe Software
 
PPTX
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
PDF
"Beyond English: Navigating the Challenges of Building a Ukrainian-language R...
Fwdays
 
PDF
Achieving Consistent and Reliable AI Code Generation - Medusa AI
medusaaico
 
PDF
Chris Elwell Woburn, MA - Passionate About IT Innovation
Chris Elwell Woburn, MA
 
PDF
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
PDF
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
OpenID AuthZEN - Analyst Briefing July 2025
David Brossard
 
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 
Building Search Using OpenSearch: Limitations and Workarounds
Sease
 
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
Presentation - Vibe Coding The Future of Tech
yanuarsinggih1
 
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
Empower Inclusion Through Accessible Java Applications
Ana-Maria Mihalceanu
 
DevBcn - Building 10x Organizations Using Modern Productivity Metrics
Justin Reock
 
HCIP-Data Center Facility Deployment V2.0 Training Material (Without Remarks ...
mcastillo49
 
Fl Studio 24.2.2 Build 4597 Crack for Windows Free Download 2025
faizk77g
 
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
NewMind AI - Journal 100 Insights After The 100th Issue
NewMind AI
 
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
Using FME to Develop Self-Service CAD Applications for a Major UK Police Force
Safe Software
 
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
"Beyond English: Navigating the Challenges of Building a Ukrainian-language R...
Fwdays
 
Achieving Consistent and Reliable AI Code Generation - Medusa AI
medusaaico
 
Chris Elwell Woburn, MA - Passionate About IT Innovation
Chris Elwell Woburn, MA
 
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 

Effecting Pure Change - How anything ever gets done in functional programming languages - Anupam Jain (S&P Global)

  • 1. EFFECTING PURE CHANGE HOW ANYTHING EVER GETS DONE IN FP ANUPAM JAIN
  • 3. 3 ❑ MEETUP: https://www.meetup.com/DelhiNCR-Haskell-And- Functional-Programming-Languages-Group ❑ TELEGRAM: https://t.me/fpncr ❑ GITHUB: https://github.com/fpncr ❑ SLACK: https://functionalprogramming.slack.com #FPNCR FPNCR
  • 5. 5 ❑ Programming with Mathematical Functions. ❑ A Function has Input and Output. ❑ Referentially Transparent ❑ A complete Program is just a function! Functional Programming
  • 6. 6 ❑ No Global State ❑ No Assignments ❑ No Statements ❑ No Input-Output Referential Transparency
  • 7. 7 ❑ Easier to Reason About ❑ Easier to Optimize ❑ Easier to Parallelize ❑ Easier to Test ❑ ??? Why?
  • 9. 9 What Happens If we Ignore the Danger
  • 10. 10 write :: String -> () read :: () -> String What could go wrong
  • 11. 11 write "Do you want a pizza?" if (read() == "Yes") orderPizza() write "Should I launch missiles?" if (read() == "Yes") launchMissiles() What could go wrong PSEUDO-CODE
  • 12. 12 write "Do you want a pizza?" if (read() == "Yes") orderPizza() write "Should I launch missiles?" if (read() == "Yes") launchMissiles() What could go wrong May be optimized away
  • 13. 13 write "Do you want a pizza?" if (read() == "Yes") orderPizza() write "Should I launch missiles?" if (read() == "Yes") launchMissiles() What could go wrong May reuse value from previous read()
  • 14. 14 OCAML let val ha = (print "ha") in ha; ha end HASKELL let ha = putStr “ha” in ha >> ha Referential Transparency is Vital ha haha
  • 16. 16 ❑ Separate “Effects” from “Values” (Hint: Strong Types are great for this) ❑ Effects are forever. No way to recover a “pure” Value. ❑ As much as possible, tag the flavor of side effects. “Print” cannot launch nukes. Contain. Not Prohibit.
  • 18. 18 ❑ React – Functional Views ❑ The Elm Architecture ❑ Functional Reactive Programming ❑ Monads and Algebraic Effects Examples
  • 19. 19 render() { let n = this.state.count return <button onClick = {setState({count:n+1})}>{n}</button> } React – Functional Views
  • 20. 20 view address model = button [onClick address Increment] [text (toString model)] update action model = case action of Increment -> model + 1 The Elm Architecture
  • 21. 21 ❑ Interface between things that are static and those that vary ❑ Forms a graph of relationships between varying things ❑ The program creates the graph, and then lets things run. Akin to cellular automata. Functional Reactive Programming
  • 22. 22 ❑ Event a – e.g. Button Clicks ❑ Behaviour a – e.g. System Time ❑ toBehaviour :: Event a -> Behaviour a ❑ mergeEvents :: Event a -> Event a -> Event a ❑ zipBehaviour :: (a -> b -> c) -> Behaviour a -> Behaviour b -> Behaviour c FRP Primitives
  • 23. 23 ❑ Event a – e.g. Button Clicks ❑ Behaviour a – e.g. System Time ❑ hold :: Event a -> Behaviour a ❑ sample :: Behaviour a -> Event b -> Event (a,b) ❑ merge :: Event a -> Event a -> Event a ❑ zip :: Behaviour a -> Behaviour b -> Behaviour (a,b) FRP Primitives
  • 24. 24 ❑ text :: Behaviour String -> IO () ❑ button :: Event () ❑ gui = do clicks <- button text hold “Not Clicked” (map (_ -> “Clicked!”) clicks) FRP GUIs
  • 26. 26 ❑ Tagged values ❑ Provide explicit control over sequencing Monads IO String
  • 27. 27 ❑ Values can be evaluated in any order (or left unevaluated). ❑ Effects need explicit control over sequencing and sharing. ❑ The only way sequencing is possible in FP is through nested functions. i.e. Callbacks. Controlling Sequencing write "Hello" (() -> write "World")
  • 28. 28 write "Do you want a pizza?" ( () -> read ( ans -> if (ans == "Yes") orderPizza ( () -> write "Should I launch missiles?" ( () -> read ( ans -> if (ans == "Yes") launchNukes () ) ) ) ) ) Continuation Passing Style
  • 29. 29 x <- foo … Sprinkle Some Syntactic Sugar foo (x -> …)
  • 30. 30 () <- write "Do you want a pizza?“ ans <- read if(ans == "Yes") () <- orderPizza () <- write "Should I launch missiles?“ ans <- read if (ans == "Yes") () <- launchNukes Sprinkle Some Syntactic Sugar write "Do you want a pizza?" (() -> read (ans -> if (ans == "Yes") orderPizza (() -> write "Should I launch missiles?" (() -> read (ans -> if (ans == "Yes") launchNukes () ) ) ) ) )
  • 31. 31 do write "Do you want a pizza?“ ans <- read if(ans == "Yes") orderPizza write "Should I launch missiles?“ ans <- read if (ans == "Yes") launchNukes Do notation
  • 32. 32 ❑ Callbacks are generally associated with Asynchronous code ❑ Do notation avoids “Callback Hell” Asynchronous Computations are Effects ajax GET “google.com" (response -> …)
  • 33. 33 do post <- ajax GET “/post/1“ map post.comments (cid -> do comment <- ajax GET “/comments/{cid}“ … ) Avoiding Callback Hell ajax GET “/post/1" (post -> map post.comments (cid -> ajax GET “/comments/{cid}" (comment -> … ) ) )
  • 34. 34 if(ans == "Yes") orderPizza else ??? Where is the Else block?
  • 35. 35 if(ans == "Yes") orderPizza else return () Where is the Else block?
  • 36. 36 Type: IO a Bind: IO a -> (a -> IO b) -> IO b Return: a -> IO a The Monad
  • 37. 37 ❑ Reader ❑ Logger ❑ State ❑ Exceptions ❑ Random ❑ … Bring Your Own Monad
  • 38. 38 Type: Reader e a :: e -> a Bind: Reader e a -> (a -> Reader e b) -> Reader e b Return: a -> Reader e a ask: Reader e e runReader: e -> Reader e a -> a Reader Monad
  • 39. 39 main = runReader myConfig do res <- foo bar res foo = do config <- ask; … bar res = do config <- ask; … Reader Monad
  • 40. 40 “Haskell” is the world’s finest imperative programming language. ~Simon Peyton Jones
  • 41. 41 “Haskell” is the world’s finest imperative programming language. ~Simon Peyton Jones (Creator of Haskell)
  • 42. 42 ❑ Like Monads, you can define your own Effects ❑ But you can define the usage and handling of the effects separately ❑ And effects compose freely (pun intended) Algebraic Effects
  • 43. 43 data Console callback = Read (String -> callback) | Write String callback handle (Read cb) = … handle (Write s cb) = … Console Effect PSEUDO-CODE
  • 44. 44 data Console callback = Read (String -> callback) | Write String callback handle (Read cb) = s = do readLine(); cb(s) handle (Write s cb) = do console.log(s); cb() Console Effect PSEUDO-CODE
  • 45. 45 handle (Write s cb) = do console.log(s); console.log(s); cb(); handle (Write s cb) = cb(); handle (Write s cb) = do cb(); console.log(s); handle (Write s cb) = do if(test(s)) console.log(s); cb(); You can do more things PSEUDO-CODE
  • 46. 46 handle (Return x) = return (x,””); handle (Write s cb) = (x,rest) = do cb(); return (x, s:rest); Returning Values from Handlers PSEUDO-CODE