SlideShare una empresa de Scribd logo
1 de 49
Descargar para leer sin conexión
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

Más contenido relacionado

La actualidad más candente

La actualidad más candente (20)

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

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

Functional Reactive Programming / Compositional Event Systems
Functional Reactive Programming / Compositional Event SystemsFunctional Reactive Programming / Compositional Event Systems
Functional Reactive Programming / Compositional Event Systems
Leonardo Borges
 

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

Programming python quick intro for schools
Programming python quick intro for schoolsProgramming python quick intro for schools
Programming python quick intro for schools
 
Introdução à Spring Web Flux
Introdução à Spring Web FluxIntrodução à Spring Web Flux
Introdução à Spring Web Flux
 
Async fun
Async funAsync fun
Async fun
 
Supercharged imperative programming with Haskell and Functional Programming
Supercharged imperative programming with Haskell and Functional ProgrammingSupercharged imperative programming with Haskell and Functional Programming
Supercharged imperative programming with Haskell and Functional Programming
 
Hierarchical free monads and software design in fp
Hierarchical free monads and software design in fpHierarchical free monads and software design in fp
Hierarchical free monads and software design in fp
 
Design problem
Design problemDesign problem
Design problem
 
InterConnect: Server Side Swift for Java Developers
InterConnect:  Server Side Swift for Java DevelopersInterConnect:  Server Side Swift for Java Developers
InterConnect: Server Side Swift for Java Developers
 
Functional Reactive Programming / Compositional Event Systems
Functional Reactive Programming / Compositional Event SystemsFunctional Reactive Programming / Compositional Event Systems
Functional Reactive Programming / Compositional Event Systems
 
Python Menu
Python MenuPython Menu
Python Menu
 
ZIO: Powerful and Principled Functional Programming in Scala
ZIO: Powerful and Principled Functional Programming in ScalaZIO: Powerful and Principled Functional Programming in Scala
ZIO: Powerful and Principled Functional Programming in Scala
 
Segmentation Faults, Page Faults, Processes, Threads, and Tasks
Segmentation Faults, Page Faults, Processes, Threads, and TasksSegmentation Faults, Page Faults, Processes, Threads, and Tasks
Segmentation Faults, Page Faults, Processes, Threads, and Tasks
 
Mining event streams with BeepBeep 3
Mining event streams with BeepBeep 3Mining event streams with BeepBeep 3
Mining event streams with BeepBeep 3
 
Introduction to java Programming
Introduction to java ProgrammingIntroduction to java Programming
Introduction to java Programming
 
Writing Faster Python 3
Writing Faster Python 3Writing Faster Python 3
Writing Faster Python 3
 
Monadologie
MonadologieMonadologie
Monadologie
 
Subtle Asynchrony by Jeff Hammond
Subtle Asynchrony by Jeff HammondSubtle Asynchrony by Jeff Hammond
Subtle Asynchrony by Jeff Hammond
 
How fast ist it really? Benchmarking in practice
How fast ist it really? Benchmarking in practiceHow fast ist it really? Benchmarking in practice
How fast ist it really? Benchmarking in practice
 
CS101- Introduction to Computing- Lecture 35
CS101- Introduction to Computing- Lecture 35CS101- Introduction to Computing- Lecture 35
CS101- Introduction to Computing- Lecture 35
 
USER DEFINE FUNCTIONS IN PYTHON
USER DEFINE FUNCTIONS IN PYTHONUSER DEFINE FUNCTIONS IN PYTHON
USER DEFINE FUNCTIONS IN PYTHON
 
Transition graph using free monads and existentials
Transition graph using free monads and existentialsTransition graph using free monads and existentials
Transition graph using free monads and existentials
 

Más de Tech Triveni

Why should a Java programmer shifts towards Functional Programming Paradigm
Why should a Java programmer shifts towards Functional Programming ParadigmWhy should a Java programmer shifts towards Functional Programming Paradigm
Why should a Java programmer shifts towards Functional Programming Paradigm
Tech Triveni
 
Programmatic Ad Tracking: Let the power of Reactive Microservices do talking
Programmatic Ad Tracking: Let the power of Reactive Microservices do talkingProgrammatic Ad Tracking: Let the power of Reactive Microservices do talking
Programmatic Ad Tracking: Let the power of Reactive Microservices do talking
Tech Triveni
 
Observability at scale with Neural Networks: A more proactive approach
Observability at scale with Neural Networks: A more proactive approachObservability at scale with Neural Networks: A more proactive approach
Observability at scale with Neural Networks: A more proactive approach
Tech Triveni
 
Semi-Supervised Insight Generation from Petabyte Scale Text Data
Semi-Supervised Insight Generation from Petabyte Scale Text DataSemi-Supervised Insight Generation from Petabyte Scale Text Data
Semi-Supervised Insight Generation from Petabyte Scale Text Data
Tech Triveni
 
Proximity Targeting at Scale using Big Data Platforms
Proximity Targeting at Scale using Big Data PlatformsProximity Targeting at Scale using Big Data Platforms
Proximity Targeting at Scale using Big Data Platforms
Tech Triveni
 
Becoming a Functional Programmer - Harit Himanshu (Nomis Solutions)
Becoming a Functional Programmer - Harit Himanshu (Nomis Solutions)Becoming a Functional Programmer - Harit Himanshu (Nomis Solutions)
Becoming a Functional Programmer - Harit Himanshu (Nomis Solutions)
Tech Triveni
 

Más de Tech Triveni (20)

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

Último

EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
Earley Information Science
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
Enterprise Knowledge
 

Último (20)

Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 

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