SlideShare une entreprise Scribd logo
1  sur  29
Télécharger pour lire hors ligne
MTL Versus Free: Deathmatch!
John A. De Goes
MTL Versus Free: Deathmatch!
• Composable Effects
• Contestant #1: MTL
• Contestant #2: Free
• Round 1: Free
• Round 2: MTL
• Round 3: ?
• The Judges Pick a Winner!
• Conclusion
Composable Effects
With as much modularity and reuse as possible, how can we represent
and compose effec7ul computa8ons in a purely-func8onal
programming language?
Contestant #1: MTL
History
1989: An Abstract View of Programming Languages — Moggi
...
1995: Monad Transformers and Modular Interpreters — Liang, Hudak, Jones
1995: Func%onal Programming with Overloading and Higher-Order Polymorphism —
Jones
class MonadTrans t where
lift :: (Monad m) => m a -> t m a
Contestant #2: Free
History (1/3)
2007: Beauty in the Beast: A Func0onal Seman0cs for the Awkward
Squad — Swierstra, Altenkirch
We demonstrate how to construct pure func2onal programs that
precisely specify the behaviour of effects.
Contestant #2: Free
History (2/3)
2008: Data Types `A La Carte — Swiestra
An addi'onal advantage of this two-step approach is that the terms
we write are pure Haskell values—informa'on we can exploit if we
are interested in debugging or reasoning about effec>ul func'ons.
data Term f a
= Pure a
| Impure (f (Term f a))
Contestant #2: Free
History (3/3)
2008: Asympto(c Improvement of Computa(ons over Free Monads —
Voigtlander
...
2015: Freer Monads, More Extensible Effects — Oleg Kiselyov
Round 1: Free
FP Nas'ness
saveFile :: forall r. Path -> File -> Eff (ModuleEff r) Unit
saveFile dir file = do
log ("Saving file" <> show (name dir) <> " to " <> show (parentDir dir))
bytes <- serialize file
rez <- httpPost ("http://cloudfiles.fooservice.com/" <> (show dir)) bytes
if (httpOK rez) then log ("Successfully saved file " <> show dir)
else let msg = "Failed to save file " <> show dir
in log msg *> throwException (error msg)
Round 1: Free
Modern Architecture for FP
Round 1: Free
Free to the Rescue
type FreeInterpreter f g = forall a. f a -> Free g a
data CloudFilesF a
= SaveFile Path File a | ListFiles Path (List Path -> a) | ...
data HttpF a = GET Path (Bytes -> a) | ...
data LogF a = Log Level String a
data SocketF a = ...
data FileIO a = ...
Round 1: Free
Composi'on of Interpreters
Round 2: MTL
MTL Strikes Back
h"ps://gist.github.com/ocharles/6b1b9440b3513a5e225e
Round 3: ?
Free(Ap) Analysis: Making Core Algebras Fast
-- A sequential composition of parallel programs in `f`:
type FreeSeqPar a = Free (FreeAp f) a
-- An optimizing interpreter:
type FreeInterpreter f g = forall a. FreeAp f a -> Free (FreeAp g) a
Allows a (ny irreducible algebra to achieve the performance of a
broad, specialized one.
Sta$cally-Typed, Purely-Func$onal,
Composable Mock Tes$ng Combinators
Why? KILL ALL THE INTEGRATION / SYSTEM TESTS!
h"ps://github.com/slamdata/purescript-mockfree
Round 3: ?
Mocking: Abstrac0ng Opera0ons
data Op a b c = Op a (b -> c)
type OpPrism f a b = forall c. PrismP (f c) (Op a b c)
-- | A helper function to create a read-only operation.
readOp :: forall f b. OpPrism f Unit b -> Free f b
readOp p = op p unit
-- | A helper function to create a write-and-read operation.
op :: forall f a b. OpPrism f a b -> a -> Free f b
op p a = liftF $ review p (Op a id)
-- | A helper function to create a write-only operation.
writeOp :: forall f a. OpPrism f a Unit -> a -> Free f Unit
writeOp p a = op p a
Round 3: ?
Mocking: Mocked Opera0ons
data MockOp f = MockOp (
forall z. (
forall a b.
OpPrism f a b -> Assertion a -> (a -> b) -> z) -> z)
type MockSpec f = State (List (MockOp f)) Unit
Round 3: ?
Mocking: Expecta0ons
type Assertion a = a -> Either String Unit
-- | Creates an assertion that asserts values are equal to the specified
-- | reference value.
assertEquals :: forall a. (Show a, Eq a) => a -> Assertion a
assertEquals e a = if e == a then Right unit else Left $ "Expected " <> show e <> " but found " <> show a
-- | Creates an expectation for an arbitrary `f` operation.
expect :: forall f a b. OpPrism f a b -> Assertion a -> (a -> b) -> MockSpec f
expect p a f = modify (Cons (MockOp (f' -> f' p a f)))
-- | Creates an expectation for a read-only `f` operation.
expectRead :: forall f b. OpPrism f Unit b -> b -> MockSpec f
expectRead p b = expect p (const $ pure unit) (const b)
-- | Creates an expectation for a write-only `f` operation.
expectWrite :: forall f a. OpPrism f a Unit -> Assertion a -> MockSpec f
expectWrite p a = expect p a (const unit)
Round 3: ?
Mocking: Mocked Opera0ons
runMock :: forall f a0. MockSpec f -> Free f a0 -> Either String a0
Round 3: ?
Mocking: Example DSL
data ConsoleF a
= WriteLine (Op String Unit a)
| ReadLine (Op Unit String a)
_WriteLine :: OpPrism ConsoleF String Unit
_WriteLine = prism' WriteLine deconstruct
where
deconstruct (WriteLine op) = Just op
deconstruct _ = Nothing
_ReadLine :: OpPrism ConsoleF Unit String
_ReadLine = prism' ReadLine deconstruct
where
deconstruct (ReadLine op) = Just op
deconstruct _ = Nothing
Round 3: ?
Mocking: Example DSL
readLine :: Free ConsoleF String
readLine = readOp _ReadLine
writeLine :: String -> Free ConsoleF Unit
writeLine s = writeOp _WriteLine s
Round 3: ?
Mocking: Example Spec
mockSpec :: MockSpec ConsoleF
mockSpec = do
expectWrite _WriteLine (assertEquals "What is your name?")
expectRead _ReadLine "World"
expectWrite _WriteLine (assertEquals "Hello, World!")
Round 3: ?
Mocking: Example Good Program
goodProgram :: Free ConsoleF Unit
goodProgram = do
writeLine "What is your name?"
name <- readLine
writeLine ("Hello, " <> name <> "!")
Success!
Round 3: ?
Mocking: Example Bad Program 1
informalProgram :: Free ConsoleF Unit
informalProgram = do
writeLine "What is your first name?"
name <- readLine
writeLine ("Hello, " <> name <> "!")
Failure: Expected "What is your name?" but found "What is your
first name?"
Round 3: ?
Mocking: Example Bad Program 2
rudeProgram :: Free ConsoleF Unit
rudeProgram = do
writeLine "What is your name?"
writeLine ("I don't care!")
Failure: Unexpected opera2on
Round 3: ?
Mocking: Example Bad Program 3
dismissiveProgram :: Free ConsoleF Unit
dismissiveProgram = do
writeLine "What is your name?"
name <- readLine
writeLine ("Goodbye, " <> name <> "!")
Failure: Expected "Hello, World!" but found "Goodbye, World!"
Round 3: ?
Mocking: Example Bad Program 4
emptyProgram :: Free ConsoleF Unit
emptyProgram = pure unit
Failure: Unexpected early termina3on (3 opera3on(s) remaining)
The Judges Pick a Winner
Winner: MTL
• Enterprise-grade
• Highest-performance
• Thoroughly explored
The Judges Pick a Winner
Runner Up: Free
• Early days for "Free" (type-safe reifica6on of computa6onal
model)
• Points toward a denota6onal future
• Algebraic programming language?
THANK YOU
Heckle me on Twi-er: @jdegoes

Contenu connexe

Tendances

The Death of Final Tagless
The Death of Final TaglessThe Death of Final Tagless
The Death of Final Tagless
John De Goes
 
Scala - where objects and functions meet
Scala - where objects and functions meetScala - where objects and functions meet
Scala - where objects and functions meet
Mario Fusco
 
"Немного о функциональном программирование в JavaScript" Алексей Коваленко
"Немного о функциональном программирование в JavaScript" Алексей Коваленко"Немного о функциональном программирование в JavaScript" Алексей Коваленко
"Немного о функциональном программирование в JavaScript" Алексей Коваленко
Fwdays
 
Java 7, 8 & 9 - Moving the language forward
Java 7, 8 & 9 - Moving the language forwardJava 7, 8 & 9 - Moving the language forward
Java 7, 8 & 9 - Moving the language forward
Mario Fusco
 

Tendances (20)

Scalaz 8 vs Akka Actors
Scalaz 8 vs Akka ActorsScalaz 8 vs Akka Actors
Scalaz 8 vs Akka Actors
 
Blazing Fast, Pure Effects without Monads — LambdaConf 2018
Blazing Fast, Pure Effects without Monads — LambdaConf 2018Blazing Fast, Pure Effects without Monads — LambdaConf 2018
Blazing Fast, Pure Effects without Monads — LambdaConf 2018
 
First-Class Patterns
First-Class PatternsFirst-Class Patterns
First-Class Patterns
 
One Monad to Rule Them All
One Monad to Rule Them AllOne Monad to Rule Them All
One Monad to Rule Them All
 
Humble introduction to category theory in haskell
Humble introduction to category theory in haskellHumble introduction to category theory in haskell
Humble introduction to category theory in haskell
 
Introduction to functional programming using Ocaml
Introduction to functional programming using OcamlIntroduction to functional programming using Ocaml
Introduction to functional programming using Ocaml
 
Functor, Apply, Applicative And Monad
Functor, Apply, Applicative And MonadFunctor, Apply, Applicative And Monad
Functor, Apply, Applicative And Monad
 
The Death of Final Tagless
The Death of Final TaglessThe Death of Final Tagless
The Death of Final Tagless
 
Scala - where objects and functions meet
Scala - where objects and functions meetScala - where objects and functions meet
Scala - where objects and functions meet
 
O caml2014 leroy-slides
O caml2014 leroy-slidesO caml2014 leroy-slides
O caml2014 leroy-slides
 
Building a Tagless Final DSL for WebGL
Building a Tagless Final DSL for WebGLBuilding a Tagless Final DSL for WebGL
Building a Tagless Final DSL for WebGL
 
"Немного о функциональном программирование в JavaScript" Алексей Коваленко
"Немного о функциональном программирование в JavaScript" Алексей Коваленко"Немного о функциональном программирование в JavaScript" Алексей Коваленко
"Немного о функциональном программирование в JavaScript" Алексей Коваленко
 
ZIO Schedule: Conquering Flakiness & Recurrence with Pure Functional Programming
ZIO Schedule: Conquering Flakiness & Recurrence with Pure Functional ProgrammingZIO Schedule: Conquering Flakiness & Recurrence with Pure Functional Programming
ZIO Schedule: Conquering Flakiness & Recurrence with Pure Functional Programming
 
Java 7, 8 & 9 - Moving the language forward
Java 7, 8 & 9 - Moving the language forwardJava 7, 8 & 9 - Moving the language forward
Java 7, 8 & 9 - Moving the language forward
 
Kotlin as a Better Java
Kotlin as a Better JavaKotlin as a Better Java
Kotlin as a Better Java
 
T3chFest 2016 - The polyglot programmer
T3chFest 2016 - The polyglot programmerT3chFest 2016 - The polyglot programmer
T3chFest 2016 - The polyglot programmer
 
Hey! There's OCaml in my Rust!
Hey! There's OCaml in my Rust!Hey! There's OCaml in my Rust!
Hey! There's OCaml in my Rust!
 
A taste of Functional Programming
A taste of Functional ProgrammingA taste of Functional Programming
A taste of Functional Programming
 
Contravariant functors in scala
Contravariant functors in scalaContravariant functors in scala
Contravariant functors in scala
 
GUL UC3M - Introduction to functional programming
GUL UC3M - Introduction to functional programmingGUL UC3M - Introduction to functional programming
GUL UC3M - Introduction to functional programming
 

En vedette

Scala Warrior and type-safe front-end development with Scala.js
Scala Warrior and type-safe front-end development with Scala.jsScala Warrior and type-safe front-end development with Scala.js
Scala Warrior and type-safe front-end development with Scala.js
takezoe
 

En vedette (12)

Streams for (Co)Free!
Streams for (Co)Free!Streams for (Co)Free!
Streams for (Co)Free!
 
Getting Started with PureScript
Getting Started with PureScriptGetting Started with PureScript
Getting Started with PureScript
 
Origins of free
Origins of freeOrigins of free
Origins of free
 
FP is coming... le 19/05/2016
FP is coming... le 19/05/2016FP is coming... le 19/05/2016
FP is coming... le 19/05/2016
 
Implementing pattern-matching in JavaScript (short version)
Implementing pattern-matching in JavaScript (short version)Implementing pattern-matching in JavaScript (short version)
Implementing pattern-matching in JavaScript (short version)
 
“Going bananas with recursion schemes for fixed point data types”
“Going bananas with recursion schemes for fixed point data types”“Going bananas with recursion schemes for fixed point data types”
“Going bananas with recursion schemes for fixed point data types”
 
Managing user's data with Spring Session
Managing user's data with Spring SessionManaging user's data with Spring Session
Managing user's data with Spring Session
 
Reducing Boilerplate and Combining Effects: A Monad Transformer Example
Reducing Boilerplate and Combining Effects: A Monad Transformer ExampleReducing Boilerplate and Combining Effects: A Monad Transformer Example
Reducing Boilerplate and Combining Effects: A Monad Transformer Example
 
Make your programs Free
Make your programs FreeMake your programs Free
Make your programs Free
 
7 key recipes for data engineering
7 key recipes for data engineering7 key recipes for data engineering
7 key recipes for data engineering
 
Scala Warrior and type-safe front-end development with Scala.js
Scala Warrior and type-safe front-end development with Scala.jsScala Warrior and type-safe front-end development with Scala.js
Scala Warrior and type-safe front-end development with Scala.js
 
Railway Oriented Programming
Railway Oriented ProgrammingRailway Oriented Programming
Railway Oriented Programming
 

Similaire à MTL Versus Free

How to start functional programming (in Scala): Day1
How to start functional programming (in Scala): Day1How to start functional programming (in Scala): Day1
How to start functional programming (in Scala): Day1
Taisuke Oe
 
Столпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай МозговойСтолпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай Мозговой
Sigma Software
 

Similaire à MTL Versus Free (20)

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
 
How to start functional programming (in Scala): Day1
How to start functional programming (in Scala): Day1How to start functional programming (in Scala): Day1
How to start functional programming (in Scala): Day1
 
Phyton Learning extracts
Phyton Learning extracts Phyton Learning extracts
Phyton Learning extracts
 
Vb.net ii
Vb.net iiVb.net ii
Vb.net ii
 
Final tagless vs free monad
Final tagless vs free monadFinal tagless vs free monad
Final tagless vs free monad
 
Peyton jones-2009-fun with-type_functions-slide
Peyton jones-2009-fun with-type_functions-slidePeyton jones-2009-fun with-type_functions-slide
Peyton jones-2009-fun with-type_functions-slide
 
1. Ch_1 SL_1_Intro to Matlab.pptx
1. Ch_1 SL_1_Intro to Matlab.pptx1. Ch_1 SL_1_Intro to Matlab.pptx
1. Ch_1 SL_1_Intro to Matlab.pptx
 
Subtle Asynchrony by Jeff Hammond
Subtle Asynchrony by Jeff HammondSubtle Asynchrony by Jeff Hammond
Subtle Asynchrony by Jeff Hammond
 
Functional programming with FSharp
Functional programming with FSharpFunctional programming with FSharp
Functional programming with FSharp
 
Slides
SlidesSlides
Slides
 
Kamil witecki asynchronous, yet readable, code
Kamil witecki asynchronous, yet readable, codeKamil witecki asynchronous, yet readable, code
Kamil witecki asynchronous, yet readable, code
 
iPython
iPythoniPython
iPython
 
cp05.pptx
cp05.pptxcp05.pptx
cp05.pptx
 
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 4
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 4Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 4
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 4
 
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part ...
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part ...Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part ...
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part ...
 
A brief introduction to lisp language
A brief introduction to lisp languageA brief introduction to lisp language
A brief introduction to lisp language
 
Столпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай МозговойСтолпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай Мозговой
 
Actors and functional_reactive_programming
Actors and functional_reactive_programmingActors and functional_reactive_programming
Actors and functional_reactive_programming
 
Advanced procedures in assembly language Full chapter ppt
Advanced procedures in assembly language Full chapter pptAdvanced procedures in assembly language Full chapter ppt
Advanced procedures in assembly language Full chapter ppt
 
10. haskell Modules
10. haskell Modules10. haskell Modules
10. haskell Modules
 

Plus de John De Goes

Refactoring Functional Type Classes
Refactoring Functional Type ClassesRefactoring Functional Type Classes
Refactoring Functional Type Classes
John De Goes
 

Plus de John De Goes (14)

Refactoring Functional Type Classes
Refactoring Functional Type ClassesRefactoring Functional Type Classes
Refactoring Functional Type Classes
 
Error Management: Future vs ZIO
Error Management: Future vs ZIOError Management: Future vs ZIO
Error Management: Future vs ZIO
 
Atomically { Delete Your Actors }
Atomically { Delete Your Actors }Atomically { Delete Your Actors }
Atomically { Delete Your Actors }
 
Scalaz Stream: Rebirth
Scalaz Stream: RebirthScalaz Stream: Rebirth
Scalaz Stream: Rebirth
 
Scalaz Stream: Rebirth
Scalaz Stream: RebirthScalaz Stream: Rebirth
Scalaz Stream: Rebirth
 
ZIO Queue
ZIO QueueZIO Queue
ZIO Queue
 
Scalaz 8: A Whole New Game
Scalaz 8: A Whole New GameScalaz 8: A Whole New Game
Scalaz 8: A Whole New Game
 
SlamData - How MongoDB Is Powering a Revolution in Visual Analytics
SlamData - How MongoDB Is Powering a Revolution in Visual AnalyticsSlamData - How MongoDB Is Powering a Revolution in Visual Analytics
SlamData - How MongoDB Is Powering a Revolution in Visual Analytics
 
The Dark Side of NoSQL
The Dark Side of NoSQLThe Dark Side of NoSQL
The Dark Side of NoSQL
 
Quirrel & R for Dummies
Quirrel & R for DummiesQuirrel & R for Dummies
Quirrel & R for Dummies
 
In-Database Predictive Analytics
In-Database Predictive AnalyticsIn-Database Predictive Analytics
In-Database Predictive Analytics
 
Analytics Maturity Model
Analytics Maturity ModelAnalytics Maturity Model
Analytics Maturity Model
 
Rise of the scientific database
Rise of the scientific databaseRise of the scientific database
Rise of the scientific database
 
Fun with automata
Fun with automataFun with automata
Fun with automata
 

Dernier

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Dernier (20)

AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024
 
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?
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
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)
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 

MTL Versus Free

  • 1. MTL Versus Free: Deathmatch! John A. De Goes
  • 2. MTL Versus Free: Deathmatch! • Composable Effects • Contestant #1: MTL • Contestant #2: Free • Round 1: Free • Round 2: MTL • Round 3: ? • The Judges Pick a Winner! • Conclusion
  • 3. Composable Effects With as much modularity and reuse as possible, how can we represent and compose effec7ul computa8ons in a purely-func8onal programming language?
  • 4. Contestant #1: MTL History 1989: An Abstract View of Programming Languages — Moggi ... 1995: Monad Transformers and Modular Interpreters — Liang, Hudak, Jones 1995: Func%onal Programming with Overloading and Higher-Order Polymorphism — Jones class MonadTrans t where lift :: (Monad m) => m a -> t m a
  • 5. Contestant #2: Free History (1/3) 2007: Beauty in the Beast: A Func0onal Seman0cs for the Awkward Squad — Swierstra, Altenkirch We demonstrate how to construct pure func2onal programs that precisely specify the behaviour of effects.
  • 6. Contestant #2: Free History (2/3) 2008: Data Types `A La Carte — Swiestra An addi'onal advantage of this two-step approach is that the terms we write are pure Haskell values—informa'on we can exploit if we are interested in debugging or reasoning about effec>ul func'ons. data Term f a = Pure a | Impure (f (Term f a))
  • 7. Contestant #2: Free History (3/3) 2008: Asympto(c Improvement of Computa(ons over Free Monads — Voigtlander ... 2015: Freer Monads, More Extensible Effects — Oleg Kiselyov
  • 8. Round 1: Free FP Nas'ness saveFile :: forall r. Path -> File -> Eff (ModuleEff r) Unit saveFile dir file = do log ("Saving file" <> show (name dir) <> " to " <> show (parentDir dir)) bytes <- serialize file rez <- httpPost ("http://cloudfiles.fooservice.com/" <> (show dir)) bytes if (httpOK rez) then log ("Successfully saved file " <> show dir) else let msg = "Failed to save file " <> show dir in log msg *> throwException (error msg)
  • 9. Round 1: Free Modern Architecture for FP
  • 10. Round 1: Free Free to the Rescue type FreeInterpreter f g = forall a. f a -> Free g a data CloudFilesF a = SaveFile Path File a | ListFiles Path (List Path -> a) | ... data HttpF a = GET Path (Bytes -> a) | ... data LogF a = Log Level String a data SocketF a = ... data FileIO a = ...
  • 11. Round 1: Free Composi'on of Interpreters
  • 12. Round 2: MTL MTL Strikes Back h"ps://gist.github.com/ocharles/6b1b9440b3513a5e225e
  • 13. Round 3: ? Free(Ap) Analysis: Making Core Algebras Fast -- A sequential composition of parallel programs in `f`: type FreeSeqPar a = Free (FreeAp f) a -- An optimizing interpreter: type FreeInterpreter f g = forall a. FreeAp f a -> Free (FreeAp g) a Allows a (ny irreducible algebra to achieve the performance of a broad, specialized one.
  • 14. Sta$cally-Typed, Purely-Func$onal, Composable Mock Tes$ng Combinators Why? KILL ALL THE INTEGRATION / SYSTEM TESTS! h"ps://github.com/slamdata/purescript-mockfree
  • 15. Round 3: ? Mocking: Abstrac0ng Opera0ons data Op a b c = Op a (b -> c) type OpPrism f a b = forall c. PrismP (f c) (Op a b c) -- | A helper function to create a read-only operation. readOp :: forall f b. OpPrism f Unit b -> Free f b readOp p = op p unit -- | A helper function to create a write-and-read operation. op :: forall f a b. OpPrism f a b -> a -> Free f b op p a = liftF $ review p (Op a id) -- | A helper function to create a write-only operation. writeOp :: forall f a. OpPrism f a Unit -> a -> Free f Unit writeOp p a = op p a
  • 16. Round 3: ? Mocking: Mocked Opera0ons data MockOp f = MockOp ( forall z. ( forall a b. OpPrism f a b -> Assertion a -> (a -> b) -> z) -> z) type MockSpec f = State (List (MockOp f)) Unit
  • 17. Round 3: ? Mocking: Expecta0ons type Assertion a = a -> Either String Unit -- | Creates an assertion that asserts values are equal to the specified -- | reference value. assertEquals :: forall a. (Show a, Eq a) => a -> Assertion a assertEquals e a = if e == a then Right unit else Left $ "Expected " <> show e <> " but found " <> show a -- | Creates an expectation for an arbitrary `f` operation. expect :: forall f a b. OpPrism f a b -> Assertion a -> (a -> b) -> MockSpec f expect p a f = modify (Cons (MockOp (f' -> f' p a f))) -- | Creates an expectation for a read-only `f` operation. expectRead :: forall f b. OpPrism f Unit b -> b -> MockSpec f expectRead p b = expect p (const $ pure unit) (const b) -- | Creates an expectation for a write-only `f` operation. expectWrite :: forall f a. OpPrism f a Unit -> Assertion a -> MockSpec f expectWrite p a = expect p a (const unit)
  • 18. Round 3: ? Mocking: Mocked Opera0ons runMock :: forall f a0. MockSpec f -> Free f a0 -> Either String a0
  • 19. Round 3: ? Mocking: Example DSL data ConsoleF a = WriteLine (Op String Unit a) | ReadLine (Op Unit String a) _WriteLine :: OpPrism ConsoleF String Unit _WriteLine = prism' WriteLine deconstruct where deconstruct (WriteLine op) = Just op deconstruct _ = Nothing _ReadLine :: OpPrism ConsoleF Unit String _ReadLine = prism' ReadLine deconstruct where deconstruct (ReadLine op) = Just op deconstruct _ = Nothing
  • 20. Round 3: ? Mocking: Example DSL readLine :: Free ConsoleF String readLine = readOp _ReadLine writeLine :: String -> Free ConsoleF Unit writeLine s = writeOp _WriteLine s
  • 21. Round 3: ? Mocking: Example Spec mockSpec :: MockSpec ConsoleF mockSpec = do expectWrite _WriteLine (assertEquals "What is your name?") expectRead _ReadLine "World" expectWrite _WriteLine (assertEquals "Hello, World!")
  • 22. Round 3: ? Mocking: Example Good Program goodProgram :: Free ConsoleF Unit goodProgram = do writeLine "What is your name?" name <- readLine writeLine ("Hello, " <> name <> "!") Success!
  • 23. Round 3: ? Mocking: Example Bad Program 1 informalProgram :: Free ConsoleF Unit informalProgram = do writeLine "What is your first name?" name <- readLine writeLine ("Hello, " <> name <> "!") Failure: Expected "What is your name?" but found "What is your first name?"
  • 24. Round 3: ? Mocking: Example Bad Program 2 rudeProgram :: Free ConsoleF Unit rudeProgram = do writeLine "What is your name?" writeLine ("I don't care!") Failure: Unexpected opera2on
  • 25. Round 3: ? Mocking: Example Bad Program 3 dismissiveProgram :: Free ConsoleF Unit dismissiveProgram = do writeLine "What is your name?" name <- readLine writeLine ("Goodbye, " <> name <> "!") Failure: Expected "Hello, World!" but found "Goodbye, World!"
  • 26. Round 3: ? Mocking: Example Bad Program 4 emptyProgram :: Free ConsoleF Unit emptyProgram = pure unit Failure: Unexpected early termina3on (3 opera3on(s) remaining)
  • 27. The Judges Pick a Winner Winner: MTL • Enterprise-grade • Highest-performance • Thoroughly explored
  • 28. The Judges Pick a Winner Runner Up: Free • Early days for "Free" (type-safe reifica6on of computa6onal model) • Points toward a denota6onal future • Algebraic programming language?
  • 29. THANK YOU Heckle me on Twi-er: @jdegoes