SlideShare une entreprise Scribd logo
1  sur  125
Run free with
the monads!
Free Monads for fun and profit
@KenScambler
#scalamelb March 2014
The problem
• Separation of concerns is paramount to software
• In FP, we try to banish effects to the peripheries of
our programs
• Results and decisions must be represented as
data, such as ADTs
• Interpretation can happen later
• Not super expressive though.
Decision/Interpretation
(tangled)
def updateAccount(user: User, db: KVStore): Unit = {
val account = db.get(user.id)
if (!account.suspended)
db.put(user.id, account.updateSpecialOffers)
else if (account.abandoned)
db.delete(user.id)
}
Decisions as data
sealed trait KVSAction
case class Put(key: String,
value: String) extends KVSAction
case class Delete(key: String) extends KVSAction
case object NoAction extends KVSAction
Decision
def chooseAction(user: User,
account: Account): KVSAction = {
if (!account.suspended)
Put(user.id, account.updateSpecialOffers)
else if (account.abandoned)
Delete(user.id)
else
NoAction
}
Interpretation
def interpret(action: KVSAction): Unit = {
action match {
case Put(key, value) => db.put(key, value)
case Delete(key) => db.delete(key)
case NoAction => ()
}
}
val account = db.get(bob,id)
interpret(chooseAction(bob, account))
How far can we push it?
• Can our pure “decision” data be as sophisticated
as a program?
• Can we create DSLs that can be run later in
different ways?
• Can we manipulate & rewrite our “program” on the
fly?
• Conditional logic?
• Loops?
• Coroutines?
How far can we push it?
def updateAccount(user: User): Unit =
for {
account <- getAccount(user.id)
_ <- when(!account.suspended)(
put(user.id, user.updated))
_ <- when(account.abandoned)(
delete(user.id))
} yield ()
The class called “Free”
• Free is a data structure
• Tree of computations
Free[F[_], A]
The class called “Free”
• Free is a data structure
• Tree of computations
Free[F[_], A]
The class called “Free”
Suspend(F[Free[F,A]])
Return(A)
Free[F[_], A]
The class called “Free”
Suspend(F[Free[F,A]])
Return(A)
Free[F[_], A]
The class called “Free”
Suspend(F[Free[F,A]])
Return(A)
Free[F[_], A]
Why “free monads”?
Why “free monads”?
Why “free monads”?
Why “free monads”?
If F[_] is a functor, Free is a
monad…… for free!
• This buys us a whole world of existing functionality
• Better abstraction
• Sequential computations
• Elegant imperative-style syntax
Remedial interlude
Functors
• Functors are things you can map over
• F[A] => (A => B) => F[B]
trait F[A] {
def map(f: A => B): F[B]
}
Functors
trait F[A] {
def map(f: A => B): F[B]
}
Functors
trait F[A] {
def map(f: A => B): F[B]
}
Functors
trait F[A] {
def map(f: A => B): F[B]
}
Monads
• Monads have a flatMap method that allows you to
chain computations together sequentially
class M[A] {
def map(f: A => B): M[B]
def flatMap(f: A => M[B]): M[B]
}
Monads
• Nesting flatmaps allows sequential actions, ignoring
the specific context!
nbaTeams.flatMap { team =>
team.players.flatMap { player =>
player.gamesPlayed.map { game =>
BasketballCard(team, player, game)
}
}
}
Monads
• Neat comprehension syntax in Scala and Haskell
• Makes it look like a regular program
for {
team <- nbaTeams
player <- team.players
game <- player.gamesPlayed
}
yield BasketballCard(team, player, game)
Back to our regularly
scheduled program…
“Free objects” in maths
• Important concept in maths!
• Many free structures in Category Theory
• Free Monoids, Free Monads, Free Categories, Free
Groups, etc
• It only counts as “free” if the free thing gets
generated in the simplest possible way
Free Blargles from
Fraxblatts
• A Fraxblatt is said to generate a Free Blargle if:
1. The Blargle doesn’t contain anything not directly
produced from a Fraxblatt
2. The Blargle doesn’t contain anything beyond what
it needs to be a Blargle
Free Blargles from
Fraxblatts
• A Fraxblatt is said to generate a Free Blargle if:
1. NO JUNK
2. NO NOISE
Making an honest monad
of it
case class Return[F[_], A](a: A) extends Free[F, A] {
def flatMap(f: A => Free[F, B]): Free[F, B] = ???
}
• Define flatMap for Return:
Making an honest monad
of it
case class Return[F[_], A](a: A) extends Free[F, A] {
def flatMap(f: A => Free[F, B]): Free[F, B] = f(a)
}
Making an honest monad
of it
• Define flatMap for Suspend:
case class Suspend[F[_], A](next: F[Free[F,A]])
extends Free[F, A] {
def flatMap(f: A => Free[F, B]): Free[F, B] = ???
}
Making an honest monad
of it
• We need to map over the functor
case class Suspend[F[_], A](next: F[Free[F,A]])
extends Free[F, A] {
def flatMap(f: A => Free[F, B]): Free[F, B] = {
F??? map ???
}
}
F[???]
Making an honest monad
of it
• “next” is the only F we have lying around
case class Suspend[F[_], A](next: F[Free[F,A]])
extends Free[F, A] {
def flatMap(f: A => Free[F, B]): Free[F, B] = {
next map {free => ???}
}
}
F[Free[F, ???]]
Making an honest monad
of it
• flatMap is almost the only thing we can do to a Free
case class Suspend[F[_], A](next: F[Free[F,A]])
extends Free[F, A] {
def flatMap(f: A => Free[F, B]): Free[F, B] = {
next map {free => free.flatMap(???)}
}
}
F[Free[F, ???]]
Making an honest monad
of it
• Mapping function f will turn our As into Free[F, B]s
case class Suspend[F[_], A](next: F[Free[F,A]])
extends Free[F, A] {
def flatMap(f: A => Free[F, B]): Free[F, B] = {
next map {free => free.flatMap(f)}
}
}
F[Free[F, B]]
Making an honest monad
of it
• Wrapping in Suspend matches the type signature!
case class Suspend[F[_], A](next: F[Free[F,A]])
extends Free[F, A] {
def flatMap(f: A => Free[F, B]): Free[F, B] = {
Suspend(next map {free => free.flatMap(f)})
}
}
Free[F, B]
Making an honest monad
of it
• Cleaning up the syntax a bit…
case class Suspend[F[_], A](next: F[Free[F,A]])
extends Free[F, A] {
def flatMap(f: A => Free[F, B]): Free[F, B] = {
Suspend(next map (_ flatMap f))
}
}
Stepping through flatMap
Let’s plug in a really simple functor and see what
happens.
case class Box[A](a: A)
Stepping through flatMap
Let’s plug in a really simple functor and see what
happens.
case class Box[A](a: A) {
def map[B](f: A => B) = Box(f(a))
}
banana
Return(banana)
Box(Return(banana))
Suspend(Box(Return(banana)))
that.flatMap(banana =>
Return(banana.peel))
that.flatMap(banana =>
Return(banana.peel))
that.flatMap(banana =>
Return(banana.peel))
that.flatMap(banana =>
Return(banana.peel))
liftF
Let’s automate creating the Suspend cell!
F[A] => Free[F, A]
=>
More flatmapping
for {
a <- liftF( Box(1) )
b <- liftF( Box(2) )
c <- liftF( Box(3) )
} yield a + b + c
for {
a <- liftF( Box(1) )
b <- liftF( Box(2) )
c <- liftF( Box(3) )
} yield a + b + c
1
for {
a <- liftF( Box(1) )
b <- liftF( Box(2) )
c <- liftF( Box(3) )
} yield a + b + c
1
for {
a <- liftF( Box(1) )
b <- liftF( Box(2) )
c <- liftF( Box(3) )
} yield a + b + c
1
for {
a <- liftF( Box(1) )
b <- liftF( Box(2) )
c <- liftF( Box(3) )
} yield a + b + c
1
for {
a <- liftF( Box(1) )
b <- liftF( Box(2) )
c <- liftF( Box(3) )
} yield a + b + c
1
for {
a <- liftF( Box(1) )
b <- liftF( Box(2) )
c <- liftF( Box(3) )
} yield a + b + c
2
for {
a <- liftF( Box(1) )
b <- liftF( Box(2) )
c <- liftF( Box(3) )
} yield a + b + c
2
for {
a <- liftF( Box(1) )
b <- liftF( Box(2) )
c <- liftF( Box(3) )
} yield a + b + c
2
for {
a <- liftF( Box(1) )
b <- liftF( Box(2) )
c <- liftF( Box(3) )
} yield a + b + c
2
for {
a <- liftF( Box(1) )
b <- liftF( Box(2) )
c <- liftF( Box(3) )
} yield a + b + c
3
for {
a <- liftF( Box(1) )
b <- liftF( Box(2) )
c <- liftF( Box(3) )
} yield a + b + c
3
for {
a <- liftF( Box(1) )
b <- liftF( Box(2) )
c <- liftF( Box(3) )
} yield a + b + c
3
for {
a <- liftF( Box(1) )
b <- liftF( Box(2) )
c <- liftF( Box(3) )
} yield a + b + c
3
for {
a <- liftF( Box(1) )
b <- liftF( Box(2) )
c <- liftF( Box(3) )
} yield a + b + c
6
Free[Box, A]
• Chain of nothings, resulting in a single value
• Not very useful!
Free[List, A]
for {
a <- liftF( List(1,2,3) )
b <- liftF( List(a,a*2) )
c <- liftF( Nil )
} yield a + b + c
for {
a <- liftF( List(1,2,3) )
b <- liftF( List(a,a*2) )
c <- liftF( Nil )
} yield a + b + c
1 2 3
for {
a <- liftF( List(1,2,3) )
b <- liftF( List(a,a*2) )
c <- liftF( Nil )
} yield a + b + c
1 2 3
for {
a <- liftF( List(1,2,3) )
b <- liftF( List(a,a*2) )
c <- liftF( Nil )
} yield a + b + c
1 2 3
for {
a <- liftF( List(1,2,3) )
b <- liftF( List(a,a*2) )
c <- liftF( Nil )
} yield a + b + c
1 2 3
for {
a <- liftF( List(1,2,3) )
b <- liftF( List(a,a*2) )
c <- liftF( Nil )
} yield a + b + c
1 2 3
for {
a <- liftF( List(1,2,3) )
b <- liftF( List(a,a*2) )
c <- liftF( Nil )
} yield a + b + c
1 2
2 4
3 6
for {
a <- liftF( List(1,2,3) )
b <- liftF( List(a,a*2) )
c <- liftF( Nil )
} yield a + b + c
1 2
2 4
3 6
for {
a <- liftF( List(1,2,3) )
b <- liftF( List(a,a*2) )
c <- liftF( Nil )
} yield a + b + c
1 2
2 4
3 6
for {
a <- liftF( List(1,2,3) )
b <- liftF( List(a,a*2) )
c <- liftF( Nil )
} yield a + b + c
1 2
2 4
3 6
for {
a <- liftF( List(1,2,3) )
b <- liftF( List(a,a*2) )
c <- liftF( Nil )
} yield a + b + c
for {
a <- liftF( List(1,2,3) )
b <- liftF( List(a,a*2) )
c <- liftF( Nil )
} yield a + b + c
for {
a <- liftF( List(1,2,3) )
b <- liftF( List(a,a*2) )
c <- liftF( Nil )
} yield a + b + c
for {
a <- liftF( List(1,2,3) )
b <- liftF( List(a,a*2) )
c <- liftF( Nil )
} yield a + b + c
Free[List,A]
• Branching tree shape, with data at the leaves
• Empty lists can terminate the tree, not just Return.
• Again, not super useful.
The functor controls the branching
factor!
Funky functions
• Functors are not just data structures that hold values
• They are computations!
• Free’s real power is unleashed when the Functor
maps over functions!
Free[Function0, A]
• No-arg functions, basically a lazy value
• Flatmapping the free composes functions
• Doesn’t actually run any code
Free[Function0, A]
for {
a <- liftF(() => 2 + 3)
b <- liftF(() => a * 2)
c <- liftF(() => a * b)
} yield a + b + c
for {
a <- liftF(() => 2 + 3)
b <- liftF(() => a * 2)
c <- liftF(() => a * b)
} yield a + b + c
=> 2 + 3
for {
a <- liftF(() => 2 + 3)
b <- liftF(() => a * 2)
c <- liftF(() => a * b)
} yield a + b + c
2 + 3=>
for {
a <- liftF(() => 2 + 3)
b <- liftF(() => a * 2)
c <- liftF(() => a * b)
} yield a + b + c
2 + 3=>
for {
a <- liftF(() => 2 + 3)
b <- liftF(() => a * 2)
c <- liftF(() => a * b)
} yield a + b + c
=>
2 + 3
for {
a <- liftF(() => 2 + 3)
b <- liftF(() => a * 2)
c <- liftF(() => a * b)
} yield a + b + c
=> => 2 + 3=>
Trampolines
Trampolines
• Believe it or not, Free[Function0,A] is incredibly
useful!
• Also known as Trampoline[A]
• Moves tail calls onto the heap, avoiding stack
overflows
• The best we can get for mutual tail recursion on the
JVM
Trampolines
• Let’s take a look at some code…
Now for the power tool
Little languages
• Small, imperative DSLs
• Don’t directly do anything, can be interpreted
many ways
• Functionally pure and type-safe
A key-value store DSL
• A bit like the KVSAction ADT way back at the start
• There’s a “type hole” for the next thing
• That means…. we can make it a Functor!
• Mechanical translation from corresponding API
functions
A key-value store DSL
sealed trait KVS[Next]
case class Put[Next](key: String,
value: String,
next: Next) extends KVS[Next]
case class Delete[Next](key: String,
next: Next) extends KVS[Next]
case class Get[Next](key: String,
onValue: String => Next) extends KVS[Next]
A key-value store DSL
sealed trait KVS[Next]
case class Put[Next](key: String,
value: String,
next: Next) extends KVS[Next]
case class Delete[Next](key: String,
next: Next) extends KVS[Next]
case class Get[Next](key: String,
onValue: String => Next) extends KVS[Next]
Just have a slot for the
next thing, if we don’t
care about a result
value
A key-value store DSL
sealed trait KVS[Next]
case class Put[Next](key: String,
value: String,
next: Next) extends KVS[Next]
case class Delete[Next](key: String,
next: Next) extends KVS[Next]
case class Get[Next](key: String,
onValue: String => Next) extends KVS[Next]
Have a Result => Next
function, if we want to
“return” some Result.
Which looks a bit like…
def put[A](key: String, value: String): Unit
def delete[A](key: String): Unit
def get[A](key: String): String
Which is a bit like…
def put[A](key: String, value: String): Unit
def delete[A](key: String): Unit
def get[A](key: String): String
A functor for our KVS
new Functor[KVS] {
def map[A,B](kvs: KVS[A])(f: A => B): KVS[B] =
kvs match {
case Put(key, value, next) =>
Put(key, value, f(next))
case Delete(key, next) =>
Delete(key, f(next))
case Get(key, onResult) =>
Get(key, onResult andThen f)
}
}
A functor for our KVS
new Functor[KVS] {
def map[A,B](kvs: KVS[A])(f: A => B): KVS[B] =
kvs match {
case Put(key, value, next) =>
Put(key, value, f(next))
case Delete(key, next) =>
Delete(key, f(next))
case Get(key, onResult) =>
Get(key, onResult andThen f)
}
}
To map over the next
value, just apply f
A functor for our KVS
new Functor[KVS] {
def map[A,B](kvs: KVS[A])(f: A => B): KVS[B] =
kvs match {
case Put(key, value, next) =>
Put(key, value, f(next))
case Delete(key, next) =>
Delete(key, f(next))
case Get(key, onResult) =>
Get(key, onResult andThen f)
}
}
To map over a function
yielding the next value,
compose f with it
Lifting into the Free
Monad
def put(key: String, value: String): Free[KVS, Unit] =
liftF( Put(key, value, ()) )
def get(key: String): Free[KVS, String] =
liftF( Get(key, identity) )
def delete(key: String): Free[KVS, Unit] =
liftF( Delete(key, ()) )
Lifting into the Free
Monad
def put(key: String, value: String): Free[KVS, Unit] =
liftF( Put(key, value, ()) )
def get(key: String): Free[KVS, String] =
liftF( Get(key, identity) )
def delete(key: String): Free[KVS, Unit] =
liftF( Delete(key, ()) )
Initialise with Unit,
when we don’t care
about the value
Lifting into the Free
Monad
def put(key: String, value: String): Free[KVS, Unit] =
liftF( Put(key, value, ()) )
def get(key: String): Free[KVS, String] =
liftF( Get(key, identity) )
def delete(key: String): Free[KVS, Unit] =
liftF( Delete(key, ()) )
Initialise with the
identity function, when
we want to return a
value
The payoff
Composable scripts
def modify(key: String,
f: String => String): Free[KVS, Unit] =
for {
v <- get(key)
_ <- put(key, f(v))
} yield ()
Harmless imperative code
val script: Free[KVS, Unit] =
for {
id <- get(“swiss-bank-account-id”)
_ <- modify(id, (_ + 1000000))
_ <- put(“bermuda-airport”, “getaway car”)
_ <- delete(“tax-records”)
} yield ()
Pure interpreters
type KVStore = Map[String, String]
def interpretPure(kvs: Free[KVS, Unit],
table: KVStore): KVStore =
kvs.resume.fold({
case Get(key, onResult) =>
interpretPure(onResult(table(key)), table)
case Put(key, value, next) =>
interpretPure(next, table + (key -> value))
case Delete(key, next) =>
interpretPure(next, table - key)
}, _ => table)
Pure interpreters
type KVStore = Map[String, String]
def interpretPure(kvs: Free[KVS, Unit],
table: KVStore): KVStore =
kvs.resume.fold({
case Get(key, onResult) =>
interpretPure(onResult(table(key)), table)
case Put(key, value, next) =>
interpretPure(next, table + (key -> value))
case Delete(key, next) =>
interpretPure(next, table - key)
}, _ => table)
KVStore is immutable
Pure interpreters
type KVStore = Map[String, String]
def interpretPure(kvs: Free[KVS, Unit],
table: KVStore): KVStore =
kvs.resume.fold({
case Get(key, onResult) =>
interpretPure(onResult(table(key)), table)
case Put(key, value, next) =>
interpretPure(next, table + (key -> value))
case Delete(key, next) =>
interpretPure(next, table - key)
}, _ => table)
F[Free[F, A]] / A
Resume and fold…
Pure interpreters
type KVStore = Map[String, String]
def interpretPure(kvs: Free[KVS, Unit],
table: KVStore): KVStore =
kvs.resume.fold({
case Get(key, onResult) =>
interpretPure(onResult(table(key)), table)
case Put(key, value, next) =>
interpretPure(next, table + (key -> value))
case Delete(key, next) =>
interpretPure(next, table - key)
}, _ => table)
KVS[Free[KVS, Unit]] / Unit
Resume and fold…
Pure interpreters
type KVStore = Map[String, String]
def interpretPure(kvs: Free[KVS, Unit],
table: KVStore): KVStore =
kvs.resume.fold({
case Get(key, onResult) =>
interpretPure(onResult(table(key)), table)
case Put(key, value, next) =>
interpretPure(next, table + (key -> value))
case Delete(key, next) =>
interpretPure(next, table - key)
}, _ => table)
When resume finally returns
Unit, return the table
Pure interpreters
type KVStore = Map[String, String]
def interpretPure(kvs: Free[KVS, Unit],
table: KVStore): KVStore =
kvs.resume.fold({
case Get(key, onResult) =>
interpretPure(onResult(table(key)), table)
case Put(key, value, next) =>
interpretPure(next, table + (key -> value))
case Delete(key, next) =>
interpretPure(next, table - key)
}, _ => table)
Effectful interpreter(s)
type KVStore = mutable.Map[String, String]
def interpretImpure(kvs: Free[KVS,Unit],
table: KVStore): Unit =
kvs.go {
case Get(key, onResult) =>
onResult(table(key))
case Put(key, value, next) =>
table += (key -> value)
next
case Delete(key, next) =>
table -= key
next
}
Effectful interpreters
type KVStore = mutable.Map[String, String]
def interpretImpure(kvs: Free[KVS,Unit],
table: KVStore): Unit =
kvs.go {
case Get(key, onResult) =>
onResult(table(key))
case Put(key, value, next) =>
table += (key -> value)
next
case Delete(key, next) =>
table -= key
next
}
Mutable map
Effectful interpreters
type KVStore = mutable.Map[String, String]
def interpretImpure(kvs: Free[KVS,Unit],
table: KVStore): Unit =
kvs.go {
case Get(key, onResult) =>
onResult(table(key))
case Put(key, value, next) =>
table += (key -> value)
next
case Delete(key, next) =>
table -= key
next
}
def go(f: F[Free[F, A]] => Free[F, A]): A
Effectful interpreter(s)
type KVStore = mutable.Map[String, String]
def interpretImpure(kvs: Free[KVS,Unit],
table: KVStore): Unit =
kvs.go {
case Get(key, onResult) =>
onResult(table(key))
case Put(key, value, next) =>
table += (key -> value)
next
case Delete(key, next) =>
table -= key
next
}
How-to summary
1. Fantasy API
2. ADT with type hole for next value
3. Functor definition for ADT
4. Lifting functions
5. Write scripts
6. Interpreter(s)
Tank game
Conclusion
• Free Monads are really powerful
• Separate decisions from interpretation, at a more
sophisticated level
• Type-safe
• Easy to use!
Conclusion
• Express your decisions in a “little language”
• Pause and resume programs, co-routine style
• Rewrite programs macro-style
• Avoid stack overflows with Trampolines
This is a great tool to have in your toolkit!
Further reading
• Awodey, Category Theory
• Bjarnason, Dead Simple Dependency Injection
• Bjarnason, Stackless Scala with Free Monads
• Doel, Many roads to Free Monads
• Ghosh, A Language and its Interpretation: Learning
Free Monads
• Gonzalez, Why Free Monads Matter
• Haskell.org, Control.Monad.Free
• Perrett, Free Monads, Part 1
• Scalaz, scalaz.Free
Further reading
https://github.com/kenbot/free
Thank you
Hope you enjoyed hearing about Free Monads!

Contenu connexe

Tendances

Refactoring Functional Type Classes
Refactoring Functional Type ClassesRefactoring Functional Type Classes
Refactoring Functional Type Classes
John De Goes
 
If You Think You Can Stay Away from Functional Programming, You Are Wrong
If You Think You Can Stay Away from Functional Programming, You Are WrongIf You Think You Can Stay Away from Functional Programming, You Are Wrong
If You Think You Can Stay Away from Functional Programming, You Are Wrong
Mario Fusco
 

Tendances (20)

Implementing the IO Monad in Scala
Implementing the IO Monad in ScalaImplementing the IO Monad in Scala
Implementing the IO Monad in Scala
 
Refactoring Functional Type Classes
Refactoring Functional Type ClassesRefactoring Functional Type Classes
Refactoring Functional Type Classes
 
Monadic Java
Monadic JavaMonadic Java
Monadic Java
 
The Functional Programming Toolkit (NDC Oslo 2019)
The Functional Programming Toolkit (NDC Oslo 2019)The Functional Programming Toolkit (NDC Oslo 2019)
The Functional Programming Toolkit (NDC Oslo 2019)
 
Sequence and Traverse - Part 1
Sequence and Traverse - Part 1Sequence and Traverse - Part 1
Sequence and Traverse - Part 1
 
Big picture of category theory in scala with deep dive into contravariant and...
Big picture of category theory in scala with deep dive into contravariant and...Big picture of category theory in scala with deep dive into contravariant and...
Big picture of category theory in scala with deep dive into contravariant and...
 
C++ classes tutorials
C++ classes tutorialsC++ classes tutorials
C++ classes tutorials
 
Hybrid inheritance
Hybrid inheritanceHybrid inheritance
Hybrid inheritance
 
Functors, Applicatives and Monads In Scala
Functors, Applicatives and Monads In ScalaFunctors, Applicatives and Monads In Scala
Functors, Applicatives and Monads In Scala
 
The Functional Programmer's Toolkit (NDC London 2019)
The Functional Programmer's Toolkit (NDC London 2019)The Functional Programmer's Toolkit (NDC London 2019)
The Functional Programmer's Toolkit (NDC London 2019)
 
Functional Programming 101 with Scala and ZIO @FunctionalWorld
Functional Programming 101 with Scala and ZIO @FunctionalWorldFunctional Programming 101 with Scala and ZIO @FunctionalWorld
Functional Programming 101 with Scala and ZIO @FunctionalWorld
 
If You Think You Can Stay Away from Functional Programming, You Are Wrong
If You Think You Can Stay Away from Functional Programming, You Are WrongIf You Think You Can Stay Away from Functional Programming, You Are Wrong
If You Think You Can Stay Away from Functional Programming, You Are Wrong
 
Virtual function in C++ Pure Virtual Function
Virtual function in C++ Pure Virtual Function Virtual function in C++ Pure Virtual Function
Virtual function in C++ Pure Virtual Function
 
From object oriented to functional domain modeling
From object oriented to functional domain modelingFrom object oriented to functional domain modeling
From object oriented to functional domain modeling
 
Zio in real world
Zio in real worldZio in real world
Zio in real world
 
Embedding Generic Monadic Transformer into Scala. [Tfp2022]
Embedding Generic Monadic Transformer into Scala. [Tfp2022]Embedding Generic Monadic Transformer into Scala. [Tfp2022]
Embedding Generic Monadic Transformer into Scala. [Tfp2022]
 
Nat, List and Option Monoids - from scratch - Combining and Folding - an example
Nat, List and Option Monoids -from scratch -Combining and Folding -an exampleNat, List and Option Monoids -from scratch -Combining and Folding -an example
Nat, List and Option Monoids - from scratch - Combining and Folding - an example
 
non-strict functions, bottom and scala by-name parameters
non-strict functions, bottom and scala by-name parametersnon-strict functions, bottom and scala by-name parameters
non-strict functions, bottom and scala by-name parameters
 
Composing an App with Free Monads (using Cats)
Composing an App with Free Monads (using Cats)Composing an App with Free Monads (using Cats)
Composing an App with Free Monads (using Cats)
 
The Terror-Free Guide to Introducing Functional Scala at Work
The Terror-Free Guide to Introducing Functional Scala at WorkThe Terror-Free Guide to Introducing Functional Scala at Work
The Terror-Free Guide to Introducing Functional Scala at Work
 

Similaire à Running Free with the Monads

ECCV2008: MAP Estimation Algorithms in Computer Vision - Part 1
ECCV2008: MAP Estimation Algorithms in Computer Vision - Part 1ECCV2008: MAP Estimation Algorithms in Computer Vision - Part 1
ECCV2008: MAP Estimation Algorithms in Computer Vision - Part 1
zukun
 
4-Regular expression to Deterministic Finite Automata (Direct method)-05-05-2...
4-Regular expression to Deterministic Finite Automata (Direct method)-05-05-2...4-Regular expression to Deterministic Finite Automata (Direct method)-05-05-2...
4-Regular expression to Deterministic Finite Automata (Direct method)-05-05-2...
venkatapranaykumarGa
 
My lecture infix-to-postfix
My lecture infix-to-postfixMy lecture infix-to-postfix
My lecture infix-to-postfix
Senthil Kumar
 

Similaire à Running Free with the Monads (20)

Fp in scala with adts part 2
Fp in scala with adts part 2Fp in scala with adts part 2
Fp in scala with adts part 2
 
The Essence of the Iterator Pattern
The Essence of the Iterator PatternThe Essence of the Iterator Pattern
The Essence of the Iterator Pattern
 
The Essence of the Iterator Pattern (pdf)
The Essence of the Iterator Pattern (pdf)The Essence of the Iterator Pattern (pdf)
The Essence of the Iterator Pattern (pdf)
 
Scala Functional Patterns
Scala Functional PatternsScala Functional Patterns
Scala Functional Patterns
 
ECCV2008: MAP Estimation Algorithms in Computer Vision - Part 1
ECCV2008: MAP Estimation Algorithms in Computer Vision - Part 1ECCV2008: MAP Estimation Algorithms in Computer Vision - Part 1
ECCV2008: MAP Estimation Algorithms in Computer Vision - Part 1
 
1.3- infix-ti-postfix.pdf
1.3- infix-ti-postfix.pdf1.3- infix-ti-postfix.pdf
1.3- infix-ti-postfix.pdf
 
Allison Kaptur: Bytes in the Machine: Inside the CPython interpreter, PyGotha...
Allison Kaptur: Bytes in the Machine: Inside the CPython interpreter, PyGotha...Allison Kaptur: Bytes in the Machine: Inside the CPython interpreter, PyGotha...
Allison Kaptur: Bytes in the Machine: Inside the CPython interpreter, PyGotha...
 
Circular queues
Circular queuesCircular queues
Circular queues
 
Will it Blend? - ScalaSyd February 2015
Will it Blend? - ScalaSyd February 2015Will it Blend? - ScalaSyd February 2015
Will it Blend? - ScalaSyd February 2015
 
4-Regular expression to Deterministic Finite Automata (Direct method)-05-05-2...
4-Regular expression to Deterministic Finite Automata (Direct method)-05-05-2...4-Regular expression to Deterministic Finite Automata (Direct method)-05-05-2...
4-Regular expression to Deterministic Finite Automata (Direct method)-05-05-2...
 
RxJava In Baby Steps
RxJava In Baby StepsRxJava In Baby Steps
RxJava In Baby Steps
 
Stacks.ppt
Stacks.pptStacks.ppt
Stacks.ppt
 
Stacks.ppt
Stacks.pptStacks.ppt
Stacks.ppt
 
Stack and queue
Stack and queueStack and queue
Stack and queue
 
Data import-cheatsheet
Data import-cheatsheetData import-cheatsheet
Data import-cheatsheet
 
Monadologie
MonadologieMonadologie
Monadologie
 
Kleisli composition, flatMap, join, map, unit - implementation and interrelat...
Kleisli composition, flatMap, join, map, unit - implementation and interrelat...Kleisli composition, flatMap, join, map, unit - implementation and interrelat...
Kleisli composition, flatMap, join, map, unit - implementation and interrelat...
 
Scala Collections : Java 8 on Steroids
Scala Collections : Java 8 on SteroidsScala Collections : Java 8 on Steroids
Scala Collections : Java 8 on Steroids
 
Fp in scala part 2
Fp in scala part 2Fp in scala part 2
Fp in scala part 2
 
My lecture infix-to-postfix
My lecture infix-to-postfixMy lecture infix-to-postfix
My lecture infix-to-postfix
 

Plus de kenbot

Plus de kenbot (11)

Grow your own tech leads
Grow your own tech leadsGrow your own tech leads
Grow your own tech leads
 
Applied category theory: the emerging science of compositionality
Applied category theory: the emerging science of compositionalityApplied category theory: the emerging science of compositionality
Applied category theory: the emerging science of compositionality
 
Responsible DI: Ditch the Frameworks
Responsible DI: Ditch the FrameworksResponsible DI: Ditch the Frameworks
Responsible DI: Ditch the Frameworks
 
FP adoption at REA
FP adoption at REAFP adoption at REA
FP adoption at REA
 
Lenses for the masses - introducing Goggles
Lenses for the masses - introducing GogglesLenses for the masses - introducing Goggles
Lenses for the masses - introducing Goggles
 
Good functional programming is good programming
Good functional programming is good programmingGood functional programming is good programming
Good functional programming is good programming
 
Data made out of functions
Data made out of functionsData made out of functions
Data made out of functions
 
Imagine a world without mocks
Imagine a world without mocksImagine a world without mocks
Imagine a world without mocks
 
2 Years of Real World FP at REA
2 Years of Real World FP at REA2 Years of Real World FP at REA
2 Years of Real World FP at REA
 
Your data structures are made of maths!
Your data structures are made of maths!Your data structures are made of maths!
Your data structures are made of maths!
 
The disaster of mutable state
The disaster of mutable stateThe disaster of mutable state
The disaster of mutable state
 

Dernier

Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Dernier (20)

Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
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...
 
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
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
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
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
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
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 

Running Free with the Monads

  • 1. Run free with the monads! Free Monads for fun and profit @KenScambler #scalamelb March 2014
  • 2. The problem • Separation of concerns is paramount to software • In FP, we try to banish effects to the peripheries of our programs • Results and decisions must be represented as data, such as ADTs • Interpretation can happen later • Not super expressive though.
  • 3. Decision/Interpretation (tangled) def updateAccount(user: User, db: KVStore): Unit = { val account = db.get(user.id) if (!account.suspended) db.put(user.id, account.updateSpecialOffers) else if (account.abandoned) db.delete(user.id) }
  • 4. Decisions as data sealed trait KVSAction case class Put(key: String, value: String) extends KVSAction case class Delete(key: String) extends KVSAction case object NoAction extends KVSAction
  • 5. Decision def chooseAction(user: User, account: Account): KVSAction = { if (!account.suspended) Put(user.id, account.updateSpecialOffers) else if (account.abandoned) Delete(user.id) else NoAction }
  • 6. Interpretation def interpret(action: KVSAction): Unit = { action match { case Put(key, value) => db.put(key, value) case Delete(key) => db.delete(key) case NoAction => () } } val account = db.get(bob,id) interpret(chooseAction(bob, account))
  • 7. How far can we push it? • Can our pure “decision” data be as sophisticated as a program? • Can we create DSLs that can be run later in different ways? • Can we manipulate & rewrite our “program” on the fly? • Conditional logic? • Loops? • Coroutines?
  • 8. How far can we push it? def updateAccount(user: User): Unit = for { account <- getAccount(user.id) _ <- when(!account.suspended)( put(user.id, user.updated)) _ <- when(account.abandoned)( delete(user.id)) } yield ()
  • 9. The class called “Free” • Free is a data structure • Tree of computations Free[F[_], A]
  • 10. The class called “Free” • Free is a data structure • Tree of computations Free[F[_], A]
  • 11. The class called “Free” Suspend(F[Free[F,A]]) Return(A) Free[F[_], A]
  • 12. The class called “Free” Suspend(F[Free[F,A]]) Return(A) Free[F[_], A]
  • 13. The class called “Free” Suspend(F[Free[F,A]]) Return(A) Free[F[_], A]
  • 17. Why “free monads”? If F[_] is a functor, Free is a monad…… for free! • This buys us a whole world of existing functionality • Better abstraction • Sequential computations • Elegant imperative-style syntax
  • 19. Functors • Functors are things you can map over • F[A] => (A => B) => F[B] trait F[A] { def map(f: A => B): F[B] }
  • 20. Functors trait F[A] { def map(f: A => B): F[B] }
  • 21. Functors trait F[A] { def map(f: A => B): F[B] }
  • 22. Functors trait F[A] { def map(f: A => B): F[B] }
  • 23. Monads • Monads have a flatMap method that allows you to chain computations together sequentially class M[A] { def map(f: A => B): M[B] def flatMap(f: A => M[B]): M[B] }
  • 24. Monads • Nesting flatmaps allows sequential actions, ignoring the specific context! nbaTeams.flatMap { team => team.players.flatMap { player => player.gamesPlayed.map { game => BasketballCard(team, player, game) } } }
  • 25. Monads • Neat comprehension syntax in Scala and Haskell • Makes it look like a regular program for { team <- nbaTeams player <- team.players game <- player.gamesPlayed } yield BasketballCard(team, player, game)
  • 26. Back to our regularly scheduled program…
  • 27. “Free objects” in maths • Important concept in maths! • Many free structures in Category Theory • Free Monoids, Free Monads, Free Categories, Free Groups, etc • It only counts as “free” if the free thing gets generated in the simplest possible way
  • 28. Free Blargles from Fraxblatts • A Fraxblatt is said to generate a Free Blargle if: 1. The Blargle doesn’t contain anything not directly produced from a Fraxblatt 2. The Blargle doesn’t contain anything beyond what it needs to be a Blargle
  • 29. Free Blargles from Fraxblatts • A Fraxblatt is said to generate a Free Blargle if: 1. NO JUNK 2. NO NOISE
  • 30. Making an honest monad of it case class Return[F[_], A](a: A) extends Free[F, A] { def flatMap(f: A => Free[F, B]): Free[F, B] = ??? } • Define flatMap for Return:
  • 31. Making an honest monad of it case class Return[F[_], A](a: A) extends Free[F, A] { def flatMap(f: A => Free[F, B]): Free[F, B] = f(a) }
  • 32. Making an honest monad of it • Define flatMap for Suspend: case class Suspend[F[_], A](next: F[Free[F,A]]) extends Free[F, A] { def flatMap(f: A => Free[F, B]): Free[F, B] = ??? }
  • 33. Making an honest monad of it • We need to map over the functor case class Suspend[F[_], A](next: F[Free[F,A]]) extends Free[F, A] { def flatMap(f: A => Free[F, B]): Free[F, B] = { F??? map ??? } } F[???]
  • 34. Making an honest monad of it • “next” is the only F we have lying around case class Suspend[F[_], A](next: F[Free[F,A]]) extends Free[F, A] { def flatMap(f: A => Free[F, B]): Free[F, B] = { next map {free => ???} } } F[Free[F, ???]]
  • 35. Making an honest monad of it • flatMap is almost the only thing we can do to a Free case class Suspend[F[_], A](next: F[Free[F,A]]) extends Free[F, A] { def flatMap(f: A => Free[F, B]): Free[F, B] = { next map {free => free.flatMap(???)} } } F[Free[F, ???]]
  • 36. Making an honest monad of it • Mapping function f will turn our As into Free[F, B]s case class Suspend[F[_], A](next: F[Free[F,A]]) extends Free[F, A] { def flatMap(f: A => Free[F, B]): Free[F, B] = { next map {free => free.flatMap(f)} } } F[Free[F, B]]
  • 37. Making an honest monad of it • Wrapping in Suspend matches the type signature! case class Suspend[F[_], A](next: F[Free[F,A]]) extends Free[F, A] { def flatMap(f: A => Free[F, B]): Free[F, B] = { Suspend(next map {free => free.flatMap(f)}) } } Free[F, B]
  • 38. Making an honest monad of it • Cleaning up the syntax a bit… case class Suspend[F[_], A](next: F[Free[F,A]]) extends Free[F, A] { def flatMap(f: A => Free[F, B]): Free[F, B] = { Suspend(next map (_ flatMap f)) } }
  • 39. Stepping through flatMap Let’s plug in a really simple functor and see what happens. case class Box[A](a: A)
  • 40. Stepping through flatMap Let’s plug in a really simple functor and see what happens. case class Box[A](a: A) { def map[B](f: A => B) = Box(f(a)) }
  • 49. liftF Let’s automate creating the Suspend cell! F[A] => Free[F, A] =>
  • 50. More flatmapping for { a <- liftF( Box(1) ) b <- liftF( Box(2) ) c <- liftF( Box(3) ) } yield a + b + c
  • 51. for { a <- liftF( Box(1) ) b <- liftF( Box(2) ) c <- liftF( Box(3) ) } yield a + b + c 1
  • 52. for { a <- liftF( Box(1) ) b <- liftF( Box(2) ) c <- liftF( Box(3) ) } yield a + b + c 1
  • 53. for { a <- liftF( Box(1) ) b <- liftF( Box(2) ) c <- liftF( Box(3) ) } yield a + b + c 1
  • 54. for { a <- liftF( Box(1) ) b <- liftF( Box(2) ) c <- liftF( Box(3) ) } yield a + b + c 1
  • 55. for { a <- liftF( Box(1) ) b <- liftF( Box(2) ) c <- liftF( Box(3) ) } yield a + b + c 1
  • 56. for { a <- liftF( Box(1) ) b <- liftF( Box(2) ) c <- liftF( Box(3) ) } yield a + b + c 2
  • 57. for { a <- liftF( Box(1) ) b <- liftF( Box(2) ) c <- liftF( Box(3) ) } yield a + b + c 2
  • 58. for { a <- liftF( Box(1) ) b <- liftF( Box(2) ) c <- liftF( Box(3) ) } yield a + b + c 2
  • 59. for { a <- liftF( Box(1) ) b <- liftF( Box(2) ) c <- liftF( Box(3) ) } yield a + b + c 2
  • 60. for { a <- liftF( Box(1) ) b <- liftF( Box(2) ) c <- liftF( Box(3) ) } yield a + b + c 3
  • 61. for { a <- liftF( Box(1) ) b <- liftF( Box(2) ) c <- liftF( Box(3) ) } yield a + b + c 3
  • 62. for { a <- liftF( Box(1) ) b <- liftF( Box(2) ) c <- liftF( Box(3) ) } yield a + b + c 3
  • 63. for { a <- liftF( Box(1) ) b <- liftF( Box(2) ) c <- liftF( Box(3) ) } yield a + b + c 3
  • 64. for { a <- liftF( Box(1) ) b <- liftF( Box(2) ) c <- liftF( Box(3) ) } yield a + b + c 6
  • 65. Free[Box, A] • Chain of nothings, resulting in a single value • Not very useful!
  • 66. Free[List, A] for { a <- liftF( List(1,2,3) ) b <- liftF( List(a,a*2) ) c <- liftF( Nil ) } yield a + b + c
  • 67. for { a <- liftF( List(1,2,3) ) b <- liftF( List(a,a*2) ) c <- liftF( Nil ) } yield a + b + c 1 2 3
  • 68. for { a <- liftF( List(1,2,3) ) b <- liftF( List(a,a*2) ) c <- liftF( Nil ) } yield a + b + c 1 2 3
  • 69. for { a <- liftF( List(1,2,3) ) b <- liftF( List(a,a*2) ) c <- liftF( Nil ) } yield a + b + c 1 2 3
  • 70. for { a <- liftF( List(1,2,3) ) b <- liftF( List(a,a*2) ) c <- liftF( Nil ) } yield a + b + c 1 2 3
  • 71. for { a <- liftF( List(1,2,3) ) b <- liftF( List(a,a*2) ) c <- liftF( Nil ) } yield a + b + c 1 2 3
  • 72. for { a <- liftF( List(1,2,3) ) b <- liftF( List(a,a*2) ) c <- liftF( Nil ) } yield a + b + c 1 2 2 4 3 6
  • 73. for { a <- liftF( List(1,2,3) ) b <- liftF( List(a,a*2) ) c <- liftF( Nil ) } yield a + b + c 1 2 2 4 3 6
  • 74. for { a <- liftF( List(1,2,3) ) b <- liftF( List(a,a*2) ) c <- liftF( Nil ) } yield a + b + c 1 2 2 4 3 6
  • 75. for { a <- liftF( List(1,2,3) ) b <- liftF( List(a,a*2) ) c <- liftF( Nil ) } yield a + b + c 1 2 2 4 3 6
  • 76. for { a <- liftF( List(1,2,3) ) b <- liftF( List(a,a*2) ) c <- liftF( Nil ) } yield a + b + c
  • 77. for { a <- liftF( List(1,2,3) ) b <- liftF( List(a,a*2) ) c <- liftF( Nil ) } yield a + b + c
  • 78. for { a <- liftF( List(1,2,3) ) b <- liftF( List(a,a*2) ) c <- liftF( Nil ) } yield a + b + c
  • 79. for { a <- liftF( List(1,2,3) ) b <- liftF( List(a,a*2) ) c <- liftF( Nil ) } yield a + b + c
  • 80. Free[List,A] • Branching tree shape, with data at the leaves • Empty lists can terminate the tree, not just Return. • Again, not super useful. The functor controls the branching factor!
  • 81. Funky functions • Functors are not just data structures that hold values • They are computations! • Free’s real power is unleashed when the Functor maps over functions!
  • 82. Free[Function0, A] • No-arg functions, basically a lazy value • Flatmapping the free composes functions • Doesn’t actually run any code
  • 83. Free[Function0, A] for { a <- liftF(() => 2 + 3) b <- liftF(() => a * 2) c <- liftF(() => a * b) } yield a + b + c
  • 84. for { a <- liftF(() => 2 + 3) b <- liftF(() => a * 2) c <- liftF(() => a * b) } yield a + b + c => 2 + 3
  • 85. for { a <- liftF(() => 2 + 3) b <- liftF(() => a * 2) c <- liftF(() => a * b) } yield a + b + c 2 + 3=>
  • 86. for { a <- liftF(() => 2 + 3) b <- liftF(() => a * 2) c <- liftF(() => a * b) } yield a + b + c 2 + 3=>
  • 87. for { a <- liftF(() => 2 + 3) b <- liftF(() => a * 2) c <- liftF(() => a * b) } yield a + b + c => 2 + 3
  • 88. for { a <- liftF(() => 2 + 3) b <- liftF(() => a * 2) c <- liftF(() => a * b) } yield a + b + c => => 2 + 3=>
  • 90. Trampolines • Believe it or not, Free[Function0,A] is incredibly useful! • Also known as Trampoline[A] • Moves tail calls onto the heap, avoiding stack overflows • The best we can get for mutual tail recursion on the JVM
  • 91. Trampolines • Let’s take a look at some code…
  • 92. Now for the power tool
  • 93. Little languages • Small, imperative DSLs • Don’t directly do anything, can be interpreted many ways • Functionally pure and type-safe
  • 94. A key-value store DSL • A bit like the KVSAction ADT way back at the start • There’s a “type hole” for the next thing • That means…. we can make it a Functor! • Mechanical translation from corresponding API functions
  • 95. A key-value store DSL sealed trait KVS[Next] case class Put[Next](key: String, value: String, next: Next) extends KVS[Next] case class Delete[Next](key: String, next: Next) extends KVS[Next] case class Get[Next](key: String, onValue: String => Next) extends KVS[Next]
  • 96. A key-value store DSL sealed trait KVS[Next] case class Put[Next](key: String, value: String, next: Next) extends KVS[Next] case class Delete[Next](key: String, next: Next) extends KVS[Next] case class Get[Next](key: String, onValue: String => Next) extends KVS[Next] Just have a slot for the next thing, if we don’t care about a result value
  • 97. A key-value store DSL sealed trait KVS[Next] case class Put[Next](key: String, value: String, next: Next) extends KVS[Next] case class Delete[Next](key: String, next: Next) extends KVS[Next] case class Get[Next](key: String, onValue: String => Next) extends KVS[Next] Have a Result => Next function, if we want to “return” some Result.
  • 98. Which looks a bit like… def put[A](key: String, value: String): Unit def delete[A](key: String): Unit def get[A](key: String): String
  • 99. Which is a bit like… def put[A](key: String, value: String): Unit def delete[A](key: String): Unit def get[A](key: String): String
  • 100. A functor for our KVS new Functor[KVS] { def map[A,B](kvs: KVS[A])(f: A => B): KVS[B] = kvs match { case Put(key, value, next) => Put(key, value, f(next)) case Delete(key, next) => Delete(key, f(next)) case Get(key, onResult) => Get(key, onResult andThen f) } }
  • 101. A functor for our KVS new Functor[KVS] { def map[A,B](kvs: KVS[A])(f: A => B): KVS[B] = kvs match { case Put(key, value, next) => Put(key, value, f(next)) case Delete(key, next) => Delete(key, f(next)) case Get(key, onResult) => Get(key, onResult andThen f) } } To map over the next value, just apply f
  • 102. A functor for our KVS new Functor[KVS] { def map[A,B](kvs: KVS[A])(f: A => B): KVS[B] = kvs match { case Put(key, value, next) => Put(key, value, f(next)) case Delete(key, next) => Delete(key, f(next)) case Get(key, onResult) => Get(key, onResult andThen f) } } To map over a function yielding the next value, compose f with it
  • 103. Lifting into the Free Monad def put(key: String, value: String): Free[KVS, Unit] = liftF( Put(key, value, ()) ) def get(key: String): Free[KVS, String] = liftF( Get(key, identity) ) def delete(key: String): Free[KVS, Unit] = liftF( Delete(key, ()) )
  • 104. Lifting into the Free Monad def put(key: String, value: String): Free[KVS, Unit] = liftF( Put(key, value, ()) ) def get(key: String): Free[KVS, String] = liftF( Get(key, identity) ) def delete(key: String): Free[KVS, Unit] = liftF( Delete(key, ()) ) Initialise with Unit, when we don’t care about the value
  • 105. Lifting into the Free Monad def put(key: String, value: String): Free[KVS, Unit] = liftF( Put(key, value, ()) ) def get(key: String): Free[KVS, String] = liftF( Get(key, identity) ) def delete(key: String): Free[KVS, Unit] = liftF( Delete(key, ()) ) Initialise with the identity function, when we want to return a value
  • 107. Composable scripts def modify(key: String, f: String => String): Free[KVS, Unit] = for { v <- get(key) _ <- put(key, f(v)) } yield ()
  • 108. Harmless imperative code val script: Free[KVS, Unit] = for { id <- get(“swiss-bank-account-id”) _ <- modify(id, (_ + 1000000)) _ <- put(“bermuda-airport”, “getaway car”) _ <- delete(“tax-records”) } yield ()
  • 109. Pure interpreters type KVStore = Map[String, String] def interpretPure(kvs: Free[KVS, Unit], table: KVStore): KVStore = kvs.resume.fold({ case Get(key, onResult) => interpretPure(onResult(table(key)), table) case Put(key, value, next) => interpretPure(next, table + (key -> value)) case Delete(key, next) => interpretPure(next, table - key) }, _ => table)
  • 110. Pure interpreters type KVStore = Map[String, String] def interpretPure(kvs: Free[KVS, Unit], table: KVStore): KVStore = kvs.resume.fold({ case Get(key, onResult) => interpretPure(onResult(table(key)), table) case Put(key, value, next) => interpretPure(next, table + (key -> value)) case Delete(key, next) => interpretPure(next, table - key) }, _ => table) KVStore is immutable
  • 111. Pure interpreters type KVStore = Map[String, String] def interpretPure(kvs: Free[KVS, Unit], table: KVStore): KVStore = kvs.resume.fold({ case Get(key, onResult) => interpretPure(onResult(table(key)), table) case Put(key, value, next) => interpretPure(next, table + (key -> value)) case Delete(key, next) => interpretPure(next, table - key) }, _ => table) F[Free[F, A]] / A Resume and fold…
  • 112. Pure interpreters type KVStore = Map[String, String] def interpretPure(kvs: Free[KVS, Unit], table: KVStore): KVStore = kvs.resume.fold({ case Get(key, onResult) => interpretPure(onResult(table(key)), table) case Put(key, value, next) => interpretPure(next, table + (key -> value)) case Delete(key, next) => interpretPure(next, table - key) }, _ => table) KVS[Free[KVS, Unit]] / Unit Resume and fold…
  • 113. Pure interpreters type KVStore = Map[String, String] def interpretPure(kvs: Free[KVS, Unit], table: KVStore): KVStore = kvs.resume.fold({ case Get(key, onResult) => interpretPure(onResult(table(key)), table) case Put(key, value, next) => interpretPure(next, table + (key -> value)) case Delete(key, next) => interpretPure(next, table - key) }, _ => table) When resume finally returns Unit, return the table
  • 114. Pure interpreters type KVStore = Map[String, String] def interpretPure(kvs: Free[KVS, Unit], table: KVStore): KVStore = kvs.resume.fold({ case Get(key, onResult) => interpretPure(onResult(table(key)), table) case Put(key, value, next) => interpretPure(next, table + (key -> value)) case Delete(key, next) => interpretPure(next, table - key) }, _ => table)
  • 115. Effectful interpreter(s) type KVStore = mutable.Map[String, String] def interpretImpure(kvs: Free[KVS,Unit], table: KVStore): Unit = kvs.go { case Get(key, onResult) => onResult(table(key)) case Put(key, value, next) => table += (key -> value) next case Delete(key, next) => table -= key next }
  • 116. Effectful interpreters type KVStore = mutable.Map[String, String] def interpretImpure(kvs: Free[KVS,Unit], table: KVStore): Unit = kvs.go { case Get(key, onResult) => onResult(table(key)) case Put(key, value, next) => table += (key -> value) next case Delete(key, next) => table -= key next } Mutable map
  • 117. Effectful interpreters type KVStore = mutable.Map[String, String] def interpretImpure(kvs: Free[KVS,Unit], table: KVStore): Unit = kvs.go { case Get(key, onResult) => onResult(table(key)) case Put(key, value, next) => table += (key -> value) next case Delete(key, next) => table -= key next } def go(f: F[Free[F, A]] => Free[F, A]): A
  • 118. Effectful interpreter(s) type KVStore = mutable.Map[String, String] def interpretImpure(kvs: Free[KVS,Unit], table: KVStore): Unit = kvs.go { case Get(key, onResult) => onResult(table(key)) case Put(key, value, next) => table += (key -> value) next case Delete(key, next) => table -= key next }
  • 119. How-to summary 1. Fantasy API 2. ADT with type hole for next value 3. Functor definition for ADT 4. Lifting functions 5. Write scripts 6. Interpreter(s)
  • 121. Conclusion • Free Monads are really powerful • Separate decisions from interpretation, at a more sophisticated level • Type-safe • Easy to use!
  • 122. Conclusion • Express your decisions in a “little language” • Pause and resume programs, co-routine style • Rewrite programs macro-style • Avoid stack overflows with Trampolines This is a great tool to have in your toolkit!
  • 123. Further reading • Awodey, Category Theory • Bjarnason, Dead Simple Dependency Injection • Bjarnason, Stackless Scala with Free Monads • Doel, Many roads to Free Monads • Ghosh, A Language and its Interpretation: Learning Free Monads • Gonzalez, Why Free Monads Matter • Haskell.org, Control.Monad.Free • Perrett, Free Monads, Part 1 • Scalaz, scalaz.Free
  • 125. Thank you Hope you enjoyed hearing about Free Monads!