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

DOC
VLSI Sequential Circuits II
PDF
PDF
Vim Hacks (OSSF)
PDF
De 0 a 100 con Bash Shell Scripting y AWK
KEY
Tres Gemas De Ruby
DOCX
Programa en C++ ( escriba 3 números y diga cual es el mayor))
PDF
Introduction to lua
VLSI Sequential Circuits II
Vim Hacks (OSSF)
De 0 a 100 con Bash Shell Scripting y AWK
Tres Gemas De Ruby
Programa en C++ ( escriba 3 números y diga cual es el mayor))
Introduction to lua

What's hot (20)

PDF
Go Concurrency
PDF
Sistemas operacionais 13
DOCX
Tugas Program C++
PDF
Taking Inspiration From The Functional World
DOCX
serverstats
PDF
Javascript - The basics
PPTX
Load-time Hacking using LD_PRELOAD
PDF
함수형사고 4장 열심히보다는현명하게
PDF
PDF
Are we ready to Go?
TXT
Xstartup
PDF
Scroll pHAT HD に美咲フォント
PDF
TrackPad Destroyer
PPTX
Perl: Coro asynchronous
PPTX
Arduino programming 101
ODP
UTAU DLL voicebank and ulauncher
PDF
Beware sharp tools
PDF
Combine vs RxSwift
PDF
tensorflow/keras model coding tutorial 勉強会
PDF
R/C++ talk at earl 2014
Go Concurrency
Sistemas operacionais 13
Tugas Program C++
Taking Inspiration From The Functional World
serverstats
Javascript - The basics
Load-time Hacking using LD_PRELOAD
함수형사고 4장 열심히보다는현명하게
Are we ready to Go?
Xstartup
Scroll pHAT HD に美咲フォント
TrackPad Destroyer
Perl: Coro asynchronous
Arduino programming 101
UTAU DLL voicebank and ulauncher
Beware sharp tools
Combine vs RxSwift
tensorflow/keras model coding tutorial 勉強会
R/C++ talk at earl 2014
Ad

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

PDF
Supercharged imperative programming with Haskell and Functional Programming
PDF
Functional programming
PPT
Introduction Functional Programming - Tech Hangout #11 - 2013.01.16
PPT
Introductory func prog
PPTX
Functional Programming Fundamentals
PDF
pure-functional-programming.pdf
PPTX
What the f is a monad?
PPTX
Functional programming
PDF
Functional Programming in F#
PDF
Introduction to functional programming (In Arabic)
KEY
Exciting JavaScript - Part II
PDF
It's the end of design patterns as we know it (and i feel fine)
PPS
Presentation of GetTogether on Functional Programming
PDF
Functional programming in Swift
PPTX
Intro to Functional Programming
PDF
Functional programming-advantages
PPTX
Good functional programming is good programming
PPT
PDF
WWX14 speech : Justin Donaldson "Promhx : Cross-platform Promises and Reactiv...
PDF
Monad Fact #6
Supercharged imperative programming with Haskell and Functional Programming
Functional programming
Introduction Functional Programming - Tech Hangout #11 - 2013.01.16
Introductory func prog
Functional Programming Fundamentals
pure-functional-programming.pdf
What the f is a monad?
Functional programming
Functional Programming in F#
Introduction to functional programming (In Arabic)
Exciting JavaScript - Part II
It's the end of design patterns as we know it (and i feel fine)
Presentation of GetTogether on Functional Programming
Functional programming in Swift
Intro to Functional Programming
Functional programming-advantages
Good functional programming is good programming
WWX14 speech : Justin Donaldson "Promhx : Cross-platform Promises and Reactiv...
Monad Fact #6
Ad

More from Tech Triveni (20)

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

Recently uploaded (20)

PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PPTX
Programs and apps: productivity, graphics, security and other tools
PPT
Teaching material agriculture food technology
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Review of recent advances in non-invasive hemoglobin estimation
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PDF
Encapsulation theory and applications.pdf
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
Spectral efficient network and resource selection model in 5G networks
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PPTX
sap open course for s4hana steps from ECC to s4
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PPTX
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
PDF
Electronic commerce courselecture one. Pdf
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
Unlocking AI with Model Context Protocol (MCP)
Network Security Unit 5.pdf for BCA BBA.
Building Integrated photovoltaic BIPV_UPV.pdf
Dropbox Q2 2025 Financial Results & Investor Presentation
Per capita expenditure prediction using model stacking based on satellite ima...
Programs and apps: productivity, graphics, security and other tools
Teaching material agriculture food technology
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Review of recent advances in non-invasive hemoglobin estimation
Understanding_Digital_Forensics_Presentation.pptx
Encapsulation theory and applications.pdf
20250228 LYD VKU AI Blended-Learning.pptx
Spectral efficient network and resource selection model in 5G networks
Digital-Transformation-Roadmap-for-Companies.pptx
sap open course for s4hana steps from ECC to s4
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
The Rise and Fall of 3GPP – Time for a Sabbatical?
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
Electronic commerce courselecture one. Pdf
Profit Center Accounting in SAP S/4HANA, S4F28 Col11

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