SlideShare a Scribd company logo
1 of 16
Download to read offline
Kleisli composition, flatMap, join, map, unit
a study/memory aid
to help learn/recall their implementation/interrelation
inspired by, and based on, the work of
Rob Norris
@tpolecat @BartoszMilewski
Bartosz Milewski Runar Bjarnason
@runarorama
Paul Chiusano
@pchiusano
VERSION 2 – UPDATED FOR SCALA 3
@philip_schwarz
slides by http://fpilluminated.com/
This slide deck is meant both for (1) those who are familiar with the monadic functions that are Kleisli
composition, unit, map, join and flatMap, and want to reinforce their knowledge (2) and as a memory aid,
for those who sometimes need a reminder of how these functions are implemented and how they
interrelate.
I learned about this subject mainly from Functional Programming in Scala, from Bartosz Milewski’s
YouTube videos (and his book), and from Rob Norris’s YouTube video, Functional Programming with Effects.
@philip_schwarz
Functional Programming in Scala
Rob Norris
@tpolecat
@BartoszMilewski
Bartosz Milewski
Paul Chiusano
Runar Bjarnason
@pchiusano
@runarorama
If you need an intro to, or refresher on, the monadic functions that are
Kleisli composition, unit, map, join and flatMap, then see the following
https://www.slideshare.net/pjschwarz/kleisli-monad-as-functor-with-pair-of-natural-transformations
https://www.slideshare.net/pjschwarz/fish-operator-anatomy
https://www.slideshare.net/pjschwarz/compositionality-and-category-theory-a-montage-of-slidestranscript-for-sections-of-rnar-bjarnasons-keynote-composing-programs
https://www.slideshare.net/pjschwarz/kleisli-composition
https://www.slideshare.net/pjschwarz/rob-norrisfunctionalprogrammingwitheffects
See the final slide of this
deck for some of the
inspiration/ideas I got from
Rob Norris’s video.
case class Insurance(name:String)
case class Car(insurance: Option[Insurance])
case class Person(car: Option[Car])
val car: Person => Option[Car] =
person => person.car
val insurance: Car => Option[Insurance] =
car => car.insurance
val toChars: String => List[Char] = _.toList
val toAscii: Char => List[Char] = _.toInt.toString.toList
assert( toChars("AB") == List('A','B'))
assert( toAscii('A') == List('6','5') )
val carInsurance: Person => Option[Insurance] =
car >=> insurance
val nonDriver= Person(car=None)
val uninsured = Person(Some(Car(insurance=None)))
val insured = Person(Some(Car(Some(Insurance("Acme")))))
assert(carInsurance(nonDriver).isEmpty)
assert(carInsurance(uninsured).isEmpty)
assert(carInsurance(insured).contains(Insurance("Acme")))
val toCharsAscii: String => List[Char] =
toChars >=> toAscii
assert(toCharsAscii("AB") == List('6','5','6','6'))
extension [A,B](f: A => Option[B])
def >=>[C](g: B => Option[C]): A => Option[C] =
a => f(a) match
case Some(b) => g(b)
case None => None
extension [A,B](f: A => List[B])
def >=>[C](g: B => List[C]): A => List[C] =
a => f(a).foldRight(List.empty[C]):
(b, cs) => g(b) ++ cs
A simple example of hand-coding Kleisli composition (i.e. >=>, the fish operator) for Option and List
Option List
We have implemented >=> by hand. Twice. Once for Option and once for List.
Now let’s make >=> generic and implement it in terms of the built-in flatMap
function of the Option and List Monads.
extension [A,B,F[_]: Monad](f: A => F[B])
def >=>[C](g: B => F[C]): A => F[C] =
a => f(a).flatMap(g)
trait Monad[F[_]]:
def unit[A](a: => A): F[A]
extension [A](fa: F[A])
def flatMap[B](f: A => F[B]): F[B]
given Monad[Option] with
def unit[A](a: => A): Option[A] = Some(a)
extension [A](fa: Option[A])
def flatMap[B](f: A => Option[B]): Option[B] = fa.flatMap(f)
given Monad[List] with
def unit[A](a: => A): List[A] = List(a)
extension [A](fa: List[A])
def flatMap[B](f: A => List[B]): List[B] = fa.flatMap(f)
Before After
>=> is hand-coded and specialised for Option and List >=> is generic and defined in terms of built-in flatMap
extension [A,B](f: A => Option[B])
def >=>[C](g: B => Option[C]): A => Option[C] =
a => f(a) match
case Some(b) => g(b)
case None => None
extension [A,B](f: A => List[B])
def >=>[C](g: B => List[C]): A => List[C] =
a => f(a).foldRight(List.empty[C]):
(b, cs) => g(b) ++ cs
I first saw the definition of >=> in a
YouTube video by Bartosz Milewski.
Bartosz Milewski’s definition of the fish operator
(Kleisli composition) in his lecture on monads.
Category Theory 10.1: Monads
@BartoszMilewski
Kleisli Composition (fish operator) >=> compose
Bind >>= flatMap
lifts a to m a (lifts A to F[A]) return unit/pure
See the next
slide for more
class Monad m where
(>>=) :: m a -> (a -> m b) -> m b
return :: a -> m a
class Monad m where
(>=>) :: (a -> m b) -> (b -> m c) -> (a -> m c)
return :: a -> m a
class Functor f where
fmap :: (a -> b) -> f a -> f b
class Functor m => Monad m where
join :: m(m a) -> ma
return :: a -> m a
>=> Kleisli Composition (aka the fish operator)
>>= Bind
f >=> g = λa -> let mb = f a in mb >>= g
= λa -> (f a) >>= g
Kleisli Composition (fish operator) >=> compose
Bind >>= flatMap
lifts a to m a (lifts A to F[A]) return unit/pure
Now let’s hand-code ourselves the flatMap
functions of the Option and List Monads.
given Monad[Option] with
def unit[A](a: => A): Option[A] = Some(a)
extension [A](fa: Option[A])
def flatMap[B](f: A => Option[B]): Option[B] = fa.flatMap(f)
given Monad[List] with
def unit[A](a: => A): List[A] = List(a)
extension [A](fa: List[A])
def flatMap[B](f: A => List[B]): List[B] = fa.flatMap(f)
given Monad[Option] with
def unit[A](a: => A): Option[A] = Some(a)
extension [A](fa: Option[A])
def flatMap[B](f: A => Option[B]): Option[B] =
fa match
case Some(a) => f(a)
case None => None
given Monad[List] with
def unit[A](a: => A): List[A] = List(a)
extension [A](fa: List[A])
def flatMap[B](f: A => List[B]): List[B] =
fa.foldRight(List.empty[B]):
(a,bs) => f(a) ++ bs
trait Monad[F[_]]: extension [A,B,F[_]: Monad](f: A => F[B])
def unit[A](a: => A): F[A] def >=>[C](g: B => F[C]): A => F[C] =
extension [A](fa: F[A]) a => f(a).flatMap(g)
def flatMap[B](f: A => F[B]): F[B]
Before After
>=> is generic and defined in terms of built-in flatMap >=> is generic and defined in terms of hand-coded flatMap
Earlier we implemented a generic >=> in terms of the built-in flatMap
function of the Option and List Monads.
Let’s do that again but this time implementing >=> in terms of the built-in
map and join functions of the Option and List Monads.
@philip_schwarz
in Scala, join is called flatten
The next slide is just a refresher on the fact that it is possible to define a
Monad in terms of unit, map and join, instead of in terms of unit and
flatMap, or in terms of unit and the fish operator. If it is the first time that
you go through this slide deck, you may want to skip the slide.
Bartosz Milewski introduces a third definition of Monad in terms of join and return, based on Functor
So this (join and return) is an alternative definition of a monad. But in this case I have to specifically say that m is a Functor, which is actually a nice thing, that I have to explicitly specify it.
…
But remember, in this case (join and return) you really have to assume that it is a functor. In this way, join is the most basic thing. Using just join and return is really more atomic than using
either bind or the Kleisli arrow, because they additionally susbsume functoriality, whereas here, functoriality is separate, separately it is a functor and separately we define join, and
separately we define return.
…
So this definition (join and return) or the definition with the Kleisli arrow, they are not used in Haskell, although they could have been. But Haskell people decided to use this (>>= and return)
as their basic definition and then for every monad they separately define join and the Kleisli arrow. So if you have a monad you can use join and the Kleisli arrow because they are defined in
the library for you. So it’s always enough to define just bind, and then fish and join will be automatically defined for you, you don’t have to do it.
#1
#2
#3
Category Theory 10.1: Monads @BartoszMilewski
given Monad[Option] with
def unit[A](a: => A): Option[A] = Some(a)
extension [A](fa: Option[A])
def map[B](f: A => B): Option[B] = fa.map(f)
extension [A](ffa: Option[Option[A]])
def join: Option[A] = ffa.flatten
given Monad[List] with
def unit[A](a: => A): List[A] = List(a)
extension [A](fa: List[A])
def map[B](f: A => B): List[B] = fa.map(f)
extension [A](ffa: List[List[A]])
def join: List[A] = ffa.flatten
Before After
>=> is generic and defined in terms of built-in flatMap >=> is generic and defined in terms of built-in map and join
given Monad[Option] with
def unit[A](a: => A): Option[A] = Some(a)
extension [A](fa: Option[A])
def flatMap[B](f: A => Option[B]): Option[B] = fa.flatMap(f)
given Monad[List] with
def unit[A](a: => A): List[A] = List(a)
extension [A](fa: List[A])
def flatMap[B](f: A => List[B]): List[B] = fa.flatMap(f)
trait Functor[F[_]]:
extension [A](fa: F[A])
def map[B](f: A => B): F[B]
trait Monad[F[_]] extends Functor[F]:
def unit[A](a: => A): F[A]
extension [A](ffa: F[F[A]])
def join: F[A]
extension [A,B,F[_]: Monad](f: A => F[B])
def >=>[C](g: B => F[C]): A => F[C] =
a => f(a).map(g).join
trait Monad[F[_]]:
def unit[A](a: => A): F[A]
extension [A](fa: F[A])
def flatMap[B](f: A => F[B]): F[B]
extension [A,B,F[_]: Monad](f: A => F[B])
def >=>[C](g: B => F[C]): A => F[C] =
a => f(a).flatMap(g)
Now let’s hand-code ourselves the map and
join functions of the Option and List Monads.
given Monad[Option] with
def unit[A](a: => A): Option[A] = Some(a)
extension [A](fa: Option[A])
def map[B](f: A => B): Option[B] = fa.map(f)
extension [A](ffa: Option[Option[A]])
def join: Option[A] = ffa.flatten
given Monad[List] with
def unit[A](a: => A): List[A] = List(a)
extension [A](fa: List[A])
def map[B](f: A => B): List[B] = fa.map(f)
extension [A](ffa: List[List[A]])
def join: List[A] = ffa.flatten
given Monad[Option] with
def unit[A](a: => A): Option[A] = Some(a)
extension [A](fa: Option[A])
def map[B](f: A => B): Option[B] = fa match
case Some(a) => Some(f(a))
case None => None
extension [A](ffa: Option[Option[A]])
def join: Option[A] = ffa match
case Some(a) => a
case None => None
given Monad[List] with
def unit[A](a: => A): List[A] = List(a)
extension [A](fa: List[A])
def map[B](f: A => B): List[B] =
fa.foldRight(List.empty[B])((a,bs) => f(a)::bs)
extension [A](ffa: List[List[A]])
def join: List[A] =
ffa.foldRight(List.empty[A])((a,bs) => a ++ bs)
trait Functor[F[_]]:
extension [A](fa: F[A])
def map[B](f: A => B): F[B]
trait Monad[F[_]] extends Functor[F]:
def unit[A](a: => A): F[A]
extension [A](ffa: F[F[A]])
def join: F[A]
extension [A,B,F[_]: Monad](f: A => F[B])
def >=>[C](g: B => F[C]): A => F[C] =
a => f(a).map(g).join
Before After
>=> is generic and defined in terms of built-in map and join >=> is generic and defined in terms of hand-coded map and join
I would like to thank Rob Norris for his great talk (see next slide), from
which I learned a lot about Kleisli composition and in which I first saw
the use of a syntax class to add the fish operator to a type class.
scale.bythebay.io
Rob Norris
Functional Programming with Effects
Rob Norris @tpolecat
the fish operator (Kleisli composition),
can be implemented using flatMap.
And this Fishy typeclass that we have derived from nothing,
using math, is Monad. So this scary thing, it just comes
naturally and I haven’t seen people talk about getting to it
from this direction. And so I hope that was helpful.
We can implement compose, the fish operator using
flatMap, so the fish operator is something we can
derive later really, the operation we need is flatMap.
We can define a syntax class
that adds these methods so that
anything that is an F[A], if there
is a Fishy instance, gets these
operations by syntax.

More Related Content

Similar to Kleisli composition, flatMap, join, map, unit - implementation and interrelation - V2 updated for Scala 3

Algebraic Data Types and Origami Patterns
Algebraic Data Types and Origami PatternsAlgebraic Data Types and Origami Patterns
Algebraic Data Types and Origami PatternsVasil Remeniuk
 
Running Free with the Monads
Running Free with the MonadsRunning Free with the Monads
Running Free with the Monadskenbot
 
Monoids, monoids, monoids
Monoids, monoids, monoidsMonoids, monoids, monoids
Monoids, monoids, monoidsLuka Jacobowitz
 
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 2Hang Zhao
 
Sequence and Traverse - Part 1
Sequence and Traverse - Part 1Sequence and Traverse - Part 1
Sequence and Traverse - Part 1Philip Schwarz
 
Monoids, Monoids, Monoids - ScalaLove 2020
Monoids, Monoids, Monoids - ScalaLove 2020Monoids, Monoids, Monoids - ScalaLove 2020
Monoids, Monoids, Monoids - ScalaLove 2020Luka Jacobowitz
 
Optics with monocle - Modeling the part and the whole
Optics with monocle - Modeling the part and the wholeOptics with monocle - Modeling the part and the whole
Optics with monocle - Modeling the part and the wholeIlan Godik
 
Oh, All the things you'll traverse
Oh, All the things you'll traverseOh, All the things you'll traverse
Oh, All the things you'll traverseLuka Jacobowitz
 
Monads and friends demystified
Monads and friends demystifiedMonads and friends demystified
Monads and friends demystifiedAlessandro Lacava
 
Monad presentation scala as a category
Monad presentation   scala as a categoryMonad presentation   scala as a category
Monad presentation scala as a categorysamthemonad
 
Why The Free Monad isn't Free
Why The Free Monad isn't FreeWhy The Free Monad isn't Free
Why The Free Monad isn't FreeKelley Robinson
 
Fp in scala part 1
Fp in scala part 1Fp in scala part 1
Fp in scala part 1Hang Zhao
 
The Essence of the Iterator Pattern
The Essence of the Iterator PatternThe Essence of the Iterator Pattern
The Essence of the Iterator PatternEric Torreborre
 
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)Eric Torreborre
 
Monad Transformers - Part 1
Monad Transformers - Part 1Monad Transformers - Part 1
Monad Transformers - Part 1Philip Schwarz
 
Taking your side effects aside
Taking your side effects asideTaking your side effects aside
Taking your side effects aside💡 Tomasz Kogut
 
From Function1#apply to Kleisli
From Function1#apply to KleisliFrom Function1#apply to Kleisli
From Function1#apply to KleisliHermann Hueck
 
Monads from Definition
Monads from DefinitionMonads from Definition
Monads from DefinitionDierk König
 
Symmetry in the interrelation of flatMap/foldMap/traverse and flatten/fold/se...
Symmetry in the interrelation of flatMap/foldMap/traverse and flatten/fold/se...Symmetry in the interrelation of flatMap/foldMap/traverse and flatten/fold/se...
Symmetry in the interrelation of flatMap/foldMap/traverse and flatten/fold/se...Philip Schwarz
 
An Introduction to Functional Programming using Haskell
An Introduction to Functional Programming using HaskellAn Introduction to Functional Programming using Haskell
An Introduction to Functional Programming using HaskellMichel Rijnders
 

Similar to Kleisli composition, flatMap, join, map, unit - implementation and interrelation - V2 updated for Scala 3 (20)

Algebraic Data Types and Origami Patterns
Algebraic Data Types and Origami PatternsAlgebraic Data Types and Origami Patterns
Algebraic Data Types and Origami Patterns
 
Running Free with the Monads
Running Free with the MonadsRunning Free with the Monads
Running Free with the Monads
 
Monoids, monoids, monoids
Monoids, monoids, monoidsMonoids, monoids, monoids
Monoids, monoids, monoids
 
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
 
Sequence and Traverse - Part 1
Sequence and Traverse - Part 1Sequence and Traverse - Part 1
Sequence and Traverse - Part 1
 
Monoids, Monoids, Monoids - ScalaLove 2020
Monoids, Monoids, Monoids - ScalaLove 2020Monoids, Monoids, Monoids - ScalaLove 2020
Monoids, Monoids, Monoids - ScalaLove 2020
 
Optics with monocle - Modeling the part and the whole
Optics with monocle - Modeling the part and the wholeOptics with monocle - Modeling the part and the whole
Optics with monocle - Modeling the part and the whole
 
Oh, All the things you'll traverse
Oh, All the things you'll traverseOh, All the things you'll traverse
Oh, All the things you'll traverse
 
Monads and friends demystified
Monads and friends demystifiedMonads and friends demystified
Monads and friends demystified
 
Monad presentation scala as a category
Monad presentation   scala as a categoryMonad presentation   scala as a category
Monad presentation scala as a category
 
Why The Free Monad isn't Free
Why The Free Monad isn't FreeWhy The Free Monad isn't Free
Why The Free Monad isn't Free
 
Fp in scala part 1
Fp in scala part 1Fp in scala part 1
Fp in scala part 1
 
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)
 
Monad Transformers - Part 1
Monad Transformers - Part 1Monad Transformers - Part 1
Monad Transformers - Part 1
 
Taking your side effects aside
Taking your side effects asideTaking your side effects aside
Taking your side effects aside
 
From Function1#apply to Kleisli
From Function1#apply to KleisliFrom Function1#apply to Kleisli
From Function1#apply to Kleisli
 
Monads from Definition
Monads from DefinitionMonads from Definition
Monads from Definition
 
Symmetry in the interrelation of flatMap/foldMap/traverse and flatten/fold/se...
Symmetry in the interrelation of flatMap/foldMap/traverse and flatten/fold/se...Symmetry in the interrelation of flatMap/foldMap/traverse and flatten/fold/se...
Symmetry in the interrelation of flatMap/foldMap/traverse and flatten/fold/se...
 
An Introduction to Functional Programming using Haskell
An Introduction to Functional Programming using HaskellAn Introduction to Functional Programming using Haskell
An Introduction to Functional Programming using Haskell
 

More from Philip Schwarz

Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
 
Folding Cheat Sheet #3 - third in a series
Folding Cheat Sheet #3 - third in a seriesFolding Cheat Sheet #3 - third in a series
Folding Cheat Sheet #3 - third in a seriesPhilip Schwarz
 
Folding Cheat Sheet #2 - second in a series
Folding Cheat Sheet #2 - second in a seriesFolding Cheat Sheet #2 - second in a series
Folding Cheat Sheet #2 - second in a seriesPhilip Schwarz
 
Folding Cheat Sheet #1 - first in a series
Folding Cheat Sheet #1 - first in a seriesFolding Cheat Sheet #1 - first in a series
Folding Cheat Sheet #1 - first in a seriesPhilip Schwarz
 
Scala Left Fold Parallelisation - Three Approaches
Scala Left Fold Parallelisation- Three ApproachesScala Left Fold Parallelisation- Three Approaches
Scala Left Fold Parallelisation - Three ApproachesPhilip Schwarz
 
Tagless Final Encoding - Algebras and Interpreters and also Programs
Tagless Final Encoding - Algebras and Interpreters and also ProgramsTagless Final Encoding - Algebras and Interpreters and also Programs
Tagless Final Encoding - Algebras and Interpreters and also ProgramsPhilip Schwarz
 
Fusing Transformations of Strict Scala Collections with Views
Fusing Transformations of Strict Scala Collections with ViewsFusing Transformations of Strict Scala Collections with Views
Fusing Transformations of Strict Scala Collections with ViewsPhilip Schwarz
 
A sighting of traverse_ function in Practical FP in Scala
A sighting of traverse_ function in Practical FP in ScalaA sighting of traverse_ function in Practical FP in Scala
A sighting of traverse_ function in Practical FP in ScalaPhilip Schwarz
 
A sighting of traverseFilter and foldMap in Practical FP in Scala
A sighting of traverseFilter and foldMap in Practical FP in ScalaA sighting of traverseFilter and foldMap in Practical FP in Scala
A sighting of traverseFilter and foldMap in Practical FP in ScalaPhilip Schwarz
 
A sighting of sequence function in Practical FP in Scala
A sighting of sequence function in Practical FP in ScalaA sighting of sequence function in Practical FP in Scala
A sighting of sequence function in Practical FP in ScalaPhilip Schwarz
 
N-Queens Combinatorial Puzzle meets Cats
N-Queens Combinatorial Puzzle meets CatsN-Queens Combinatorial Puzzle meets Cats
N-Queens Combinatorial Puzzle meets CatsPhilip Schwarz
 
The aggregate function - from sequential and parallel folds to parallel aggre...
The aggregate function - from sequential and parallel folds to parallel aggre...The aggregate function - from sequential and parallel folds to parallel aggre...
The aggregate function - from sequential and parallel folds to parallel aggre...Philip Schwarz
 
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 examplePhilip Schwarz
 
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 examplePhilip Schwarz
 
The Sieve of Eratosthenes - Part II - Genuine versus Unfaithful Sieve - Haske...
The Sieve of Eratosthenes - Part II - Genuine versus Unfaithful Sieve - Haske...The Sieve of Eratosthenes - Part II - Genuine versus Unfaithful Sieve - Haske...
The Sieve of Eratosthenes - Part II - Genuine versus Unfaithful Sieve - Haske...Philip Schwarz
 
Sum and Product Types - The Fruit Salad & Fruit Snack Example - From F# to Ha...
Sum and Product Types -The Fruit Salad & Fruit Snack Example - From F# to Ha...Sum and Product Types -The Fruit Salad & Fruit Snack Example - From F# to Ha...
Sum and Product Types - The Fruit Salad & Fruit Snack Example - From F# to Ha...Philip Schwarz
 
Algebraic Data Types for Data Oriented Programming - From Haskell and Scala t...
Algebraic Data Types forData Oriented Programming - From Haskell and Scala t...Algebraic Data Types forData Oriented Programming - From Haskell and Scala t...
Algebraic Data Types for Data Oriented Programming - From Haskell and Scala t...Philip Schwarz
 
Jordan Peterson - The pursuit of meaning and related ethical axioms
Jordan Peterson - The pursuit of meaning and related ethical axiomsJordan Peterson - The pursuit of meaning and related ethical axioms
Jordan Peterson - The pursuit of meaning and related ethical axiomsPhilip Schwarz
 
Defining filter using (a) recursion (b) folding (c) folding with S, B and I c...
Defining filter using (a) recursion (b) folding (c) folding with S, B and I c...Defining filter using (a) recursion (b) folding (c) folding with S, B and I c...
Defining filter using (a) recursion (b) folding (c) folding with S, B and I c...Philip Schwarz
 
Defining filter using (a) recursion (b) folding with S, B and I combinators (...
Defining filter using (a) recursion (b) folding with S, B and I combinators (...Defining filter using (a) recursion (b) folding with S, B and I combinators (...
Defining filter using (a) recursion (b) folding with S, B and I combinators (...Philip Schwarz
 

More from Philip Schwarz (20)

Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 
Folding Cheat Sheet #3 - third in a series
Folding Cheat Sheet #3 - third in a seriesFolding Cheat Sheet #3 - third in a series
Folding Cheat Sheet #3 - third in a series
 
Folding Cheat Sheet #2 - second in a series
Folding Cheat Sheet #2 - second in a seriesFolding Cheat Sheet #2 - second in a series
Folding Cheat Sheet #2 - second in a series
 
Folding Cheat Sheet #1 - first in a series
Folding Cheat Sheet #1 - first in a seriesFolding Cheat Sheet #1 - first in a series
Folding Cheat Sheet #1 - first in a series
 
Scala Left Fold Parallelisation - Three Approaches
Scala Left Fold Parallelisation- Three ApproachesScala Left Fold Parallelisation- Three Approaches
Scala Left Fold Parallelisation - Three Approaches
 
Tagless Final Encoding - Algebras and Interpreters and also Programs
Tagless Final Encoding - Algebras and Interpreters and also ProgramsTagless Final Encoding - Algebras and Interpreters and also Programs
Tagless Final Encoding - Algebras and Interpreters and also Programs
 
Fusing Transformations of Strict Scala Collections with Views
Fusing Transformations of Strict Scala Collections with ViewsFusing Transformations of Strict Scala Collections with Views
Fusing Transformations of Strict Scala Collections with Views
 
A sighting of traverse_ function in Practical FP in Scala
A sighting of traverse_ function in Practical FP in ScalaA sighting of traverse_ function in Practical FP in Scala
A sighting of traverse_ function in Practical FP in Scala
 
A sighting of traverseFilter and foldMap in Practical FP in Scala
A sighting of traverseFilter and foldMap in Practical FP in ScalaA sighting of traverseFilter and foldMap in Practical FP in Scala
A sighting of traverseFilter and foldMap in Practical FP in Scala
 
A sighting of sequence function in Practical FP in Scala
A sighting of sequence function in Practical FP in ScalaA sighting of sequence function in Practical FP in Scala
A sighting of sequence function in Practical FP in Scala
 
N-Queens Combinatorial Puzzle meets Cats
N-Queens Combinatorial Puzzle meets CatsN-Queens Combinatorial Puzzle meets Cats
N-Queens Combinatorial Puzzle meets Cats
 
The aggregate function - from sequential and parallel folds to parallel aggre...
The aggregate function - from sequential and parallel folds to parallel aggre...The aggregate function - from sequential and parallel folds to parallel aggre...
The aggregate function - from sequential and parallel folds to parallel aggre...
 
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
 
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
 
The Sieve of Eratosthenes - Part II - Genuine versus Unfaithful Sieve - Haske...
The Sieve of Eratosthenes - Part II - Genuine versus Unfaithful Sieve - Haske...The Sieve of Eratosthenes - Part II - Genuine versus Unfaithful Sieve - Haske...
The Sieve of Eratosthenes - Part II - Genuine versus Unfaithful Sieve - Haske...
 
Sum and Product Types - The Fruit Salad & Fruit Snack Example - From F# to Ha...
Sum and Product Types -The Fruit Salad & Fruit Snack Example - From F# to Ha...Sum and Product Types -The Fruit Salad & Fruit Snack Example - From F# to Ha...
Sum and Product Types - The Fruit Salad & Fruit Snack Example - From F# to Ha...
 
Algebraic Data Types for Data Oriented Programming - From Haskell and Scala t...
Algebraic Data Types forData Oriented Programming - From Haskell and Scala t...Algebraic Data Types forData Oriented Programming - From Haskell and Scala t...
Algebraic Data Types for Data Oriented Programming - From Haskell and Scala t...
 
Jordan Peterson - The pursuit of meaning and related ethical axioms
Jordan Peterson - The pursuit of meaning and related ethical axiomsJordan Peterson - The pursuit of meaning and related ethical axioms
Jordan Peterson - The pursuit of meaning and related ethical axioms
 
Defining filter using (a) recursion (b) folding (c) folding with S, B and I c...
Defining filter using (a) recursion (b) folding (c) folding with S, B and I c...Defining filter using (a) recursion (b) folding (c) folding with S, B and I c...
Defining filter using (a) recursion (b) folding (c) folding with S, B and I c...
 
Defining filter using (a) recursion (b) folding with S, B and I combinators (...
Defining filter using (a) recursion (b) folding with S, B and I combinators (...Defining filter using (a) recursion (b) folding with S, B and I combinators (...
Defining filter using (a) recursion (b) folding with S, B and I combinators (...
 

Recently uploaded

BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作qr0udbr0
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesŁukasz Chruściel
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Velvetech LLC
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Hr365.us smith
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Matt Ray
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odishasmiwainfosol
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...OnePlan Solutions
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样umasea
 

Recently uploaded (20)

BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New Features
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
 
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
 

Kleisli composition, flatMap, join, map, unit - implementation and interrelation - V2 updated for Scala 3

  • 1. Kleisli composition, flatMap, join, map, unit a study/memory aid to help learn/recall their implementation/interrelation inspired by, and based on, the work of Rob Norris @tpolecat @BartoszMilewski Bartosz Milewski Runar Bjarnason @runarorama Paul Chiusano @pchiusano VERSION 2 – UPDATED FOR SCALA 3 @philip_schwarz slides by http://fpilluminated.com/
  • 2. This slide deck is meant both for (1) those who are familiar with the monadic functions that are Kleisli composition, unit, map, join and flatMap, and want to reinforce their knowledge (2) and as a memory aid, for those who sometimes need a reminder of how these functions are implemented and how they interrelate. I learned about this subject mainly from Functional Programming in Scala, from Bartosz Milewski’s YouTube videos (and his book), and from Rob Norris’s YouTube video, Functional Programming with Effects. @philip_schwarz Functional Programming in Scala Rob Norris @tpolecat @BartoszMilewski Bartosz Milewski Paul Chiusano Runar Bjarnason @pchiusano @runarorama If you need an intro to, or refresher on, the monadic functions that are Kleisli composition, unit, map, join and flatMap, then see the following https://www.slideshare.net/pjschwarz/kleisli-monad-as-functor-with-pair-of-natural-transformations https://www.slideshare.net/pjschwarz/fish-operator-anatomy https://www.slideshare.net/pjschwarz/compositionality-and-category-theory-a-montage-of-slidestranscript-for-sections-of-rnar-bjarnasons-keynote-composing-programs https://www.slideshare.net/pjschwarz/kleisli-composition https://www.slideshare.net/pjschwarz/rob-norrisfunctionalprogrammingwitheffects See the final slide of this deck for some of the inspiration/ideas I got from Rob Norris’s video.
  • 3. case class Insurance(name:String) case class Car(insurance: Option[Insurance]) case class Person(car: Option[Car]) val car: Person => Option[Car] = person => person.car val insurance: Car => Option[Insurance] = car => car.insurance val toChars: String => List[Char] = _.toList val toAscii: Char => List[Char] = _.toInt.toString.toList assert( toChars("AB") == List('A','B')) assert( toAscii('A') == List('6','5') ) val carInsurance: Person => Option[Insurance] = car >=> insurance val nonDriver= Person(car=None) val uninsured = Person(Some(Car(insurance=None))) val insured = Person(Some(Car(Some(Insurance("Acme"))))) assert(carInsurance(nonDriver).isEmpty) assert(carInsurance(uninsured).isEmpty) assert(carInsurance(insured).contains(Insurance("Acme"))) val toCharsAscii: String => List[Char] = toChars >=> toAscii assert(toCharsAscii("AB") == List('6','5','6','6')) extension [A,B](f: A => Option[B]) def >=>[C](g: B => Option[C]): A => Option[C] = a => f(a) match case Some(b) => g(b) case None => None extension [A,B](f: A => List[B]) def >=>[C](g: B => List[C]): A => List[C] = a => f(a).foldRight(List.empty[C]): (b, cs) => g(b) ++ cs A simple example of hand-coding Kleisli composition (i.e. >=>, the fish operator) for Option and List Option List
  • 4. We have implemented >=> by hand. Twice. Once for Option and once for List. Now let’s make >=> generic and implement it in terms of the built-in flatMap function of the Option and List Monads.
  • 5. extension [A,B,F[_]: Monad](f: A => F[B]) def >=>[C](g: B => F[C]): A => F[C] = a => f(a).flatMap(g) trait Monad[F[_]]: def unit[A](a: => A): F[A] extension [A](fa: F[A]) def flatMap[B](f: A => F[B]): F[B] given Monad[Option] with def unit[A](a: => A): Option[A] = Some(a) extension [A](fa: Option[A]) def flatMap[B](f: A => Option[B]): Option[B] = fa.flatMap(f) given Monad[List] with def unit[A](a: => A): List[A] = List(a) extension [A](fa: List[A]) def flatMap[B](f: A => List[B]): List[B] = fa.flatMap(f) Before After >=> is hand-coded and specialised for Option and List >=> is generic and defined in terms of built-in flatMap extension [A,B](f: A => Option[B]) def >=>[C](g: B => Option[C]): A => Option[C] = a => f(a) match case Some(b) => g(b) case None => None extension [A,B](f: A => List[B]) def >=>[C](g: B => List[C]): A => List[C] = a => f(a).foldRight(List.empty[C]): (b, cs) => g(b) ++ cs
  • 6. I first saw the definition of >=> in a YouTube video by Bartosz Milewski. Bartosz Milewski’s definition of the fish operator (Kleisli composition) in his lecture on monads. Category Theory 10.1: Monads @BartoszMilewski Kleisli Composition (fish operator) >=> compose Bind >>= flatMap lifts a to m a (lifts A to F[A]) return unit/pure See the next slide for more
  • 7. class Monad m where (>>=) :: m a -> (a -> m b) -> m b return :: a -> m a class Monad m where (>=>) :: (a -> m b) -> (b -> m c) -> (a -> m c) return :: a -> m a class Functor f where fmap :: (a -> b) -> f a -> f b class Functor m => Monad m where join :: m(m a) -> ma return :: a -> m a >=> Kleisli Composition (aka the fish operator) >>= Bind f >=> g = λa -> let mb = f a in mb >>= g = λa -> (f a) >>= g Kleisli Composition (fish operator) >=> compose Bind >>= flatMap lifts a to m a (lifts A to F[A]) return unit/pure
  • 8. Now let’s hand-code ourselves the flatMap functions of the Option and List Monads.
  • 9. given Monad[Option] with def unit[A](a: => A): Option[A] = Some(a) extension [A](fa: Option[A]) def flatMap[B](f: A => Option[B]): Option[B] = fa.flatMap(f) given Monad[List] with def unit[A](a: => A): List[A] = List(a) extension [A](fa: List[A]) def flatMap[B](f: A => List[B]): List[B] = fa.flatMap(f) given Monad[Option] with def unit[A](a: => A): Option[A] = Some(a) extension [A](fa: Option[A]) def flatMap[B](f: A => Option[B]): Option[B] = fa match case Some(a) => f(a) case None => None given Monad[List] with def unit[A](a: => A): List[A] = List(a) extension [A](fa: List[A]) def flatMap[B](f: A => List[B]): List[B] = fa.foldRight(List.empty[B]): (a,bs) => f(a) ++ bs trait Monad[F[_]]: extension [A,B,F[_]: Monad](f: A => F[B]) def unit[A](a: => A): F[A] def >=>[C](g: B => F[C]): A => F[C] = extension [A](fa: F[A]) a => f(a).flatMap(g) def flatMap[B](f: A => F[B]): F[B] Before After >=> is generic and defined in terms of built-in flatMap >=> is generic and defined in terms of hand-coded flatMap
  • 10. Earlier we implemented a generic >=> in terms of the built-in flatMap function of the Option and List Monads. Let’s do that again but this time implementing >=> in terms of the built-in map and join functions of the Option and List Monads. @philip_schwarz in Scala, join is called flatten The next slide is just a refresher on the fact that it is possible to define a Monad in terms of unit, map and join, instead of in terms of unit and flatMap, or in terms of unit and the fish operator. If it is the first time that you go through this slide deck, you may want to skip the slide.
  • 11. Bartosz Milewski introduces a third definition of Monad in terms of join and return, based on Functor So this (join and return) is an alternative definition of a monad. But in this case I have to specifically say that m is a Functor, which is actually a nice thing, that I have to explicitly specify it. … But remember, in this case (join and return) you really have to assume that it is a functor. In this way, join is the most basic thing. Using just join and return is really more atomic than using either bind or the Kleisli arrow, because they additionally susbsume functoriality, whereas here, functoriality is separate, separately it is a functor and separately we define join, and separately we define return. … So this definition (join and return) or the definition with the Kleisli arrow, they are not used in Haskell, although they could have been. But Haskell people decided to use this (>>= and return) as their basic definition and then for every monad they separately define join and the Kleisli arrow. So if you have a monad you can use join and the Kleisli arrow because they are defined in the library for you. So it’s always enough to define just bind, and then fish and join will be automatically defined for you, you don’t have to do it. #1 #2 #3 Category Theory 10.1: Monads @BartoszMilewski
  • 12. given Monad[Option] with def unit[A](a: => A): Option[A] = Some(a) extension [A](fa: Option[A]) def map[B](f: A => B): Option[B] = fa.map(f) extension [A](ffa: Option[Option[A]]) def join: Option[A] = ffa.flatten given Monad[List] with def unit[A](a: => A): List[A] = List(a) extension [A](fa: List[A]) def map[B](f: A => B): List[B] = fa.map(f) extension [A](ffa: List[List[A]]) def join: List[A] = ffa.flatten Before After >=> is generic and defined in terms of built-in flatMap >=> is generic and defined in terms of built-in map and join given Monad[Option] with def unit[A](a: => A): Option[A] = Some(a) extension [A](fa: Option[A]) def flatMap[B](f: A => Option[B]): Option[B] = fa.flatMap(f) given Monad[List] with def unit[A](a: => A): List[A] = List(a) extension [A](fa: List[A]) def flatMap[B](f: A => List[B]): List[B] = fa.flatMap(f) trait Functor[F[_]]: extension [A](fa: F[A]) def map[B](f: A => B): F[B] trait Monad[F[_]] extends Functor[F]: def unit[A](a: => A): F[A] extension [A](ffa: F[F[A]]) def join: F[A] extension [A,B,F[_]: Monad](f: A => F[B]) def >=>[C](g: B => F[C]): A => F[C] = a => f(a).map(g).join trait Monad[F[_]]: def unit[A](a: => A): F[A] extension [A](fa: F[A]) def flatMap[B](f: A => F[B]): F[B] extension [A,B,F[_]: Monad](f: A => F[B]) def >=>[C](g: B => F[C]): A => F[C] = a => f(a).flatMap(g)
  • 13. Now let’s hand-code ourselves the map and join functions of the Option and List Monads.
  • 14. given Monad[Option] with def unit[A](a: => A): Option[A] = Some(a) extension [A](fa: Option[A]) def map[B](f: A => B): Option[B] = fa.map(f) extension [A](ffa: Option[Option[A]]) def join: Option[A] = ffa.flatten given Monad[List] with def unit[A](a: => A): List[A] = List(a) extension [A](fa: List[A]) def map[B](f: A => B): List[B] = fa.map(f) extension [A](ffa: List[List[A]]) def join: List[A] = ffa.flatten given Monad[Option] with def unit[A](a: => A): Option[A] = Some(a) extension [A](fa: Option[A]) def map[B](f: A => B): Option[B] = fa match case Some(a) => Some(f(a)) case None => None extension [A](ffa: Option[Option[A]]) def join: Option[A] = ffa match case Some(a) => a case None => None given Monad[List] with def unit[A](a: => A): List[A] = List(a) extension [A](fa: List[A]) def map[B](f: A => B): List[B] = fa.foldRight(List.empty[B])((a,bs) => f(a)::bs) extension [A](ffa: List[List[A]]) def join: List[A] = ffa.foldRight(List.empty[A])((a,bs) => a ++ bs) trait Functor[F[_]]: extension [A](fa: F[A]) def map[B](f: A => B): F[B] trait Monad[F[_]] extends Functor[F]: def unit[A](a: => A): F[A] extension [A](ffa: F[F[A]]) def join: F[A] extension [A,B,F[_]: Monad](f: A => F[B]) def >=>[C](g: B => F[C]): A => F[C] = a => f(a).map(g).join Before After >=> is generic and defined in terms of built-in map and join >=> is generic and defined in terms of hand-coded map and join
  • 15. I would like to thank Rob Norris for his great talk (see next slide), from which I learned a lot about Kleisli composition and in which I first saw the use of a syntax class to add the fish operator to a type class.
  • 16. scale.bythebay.io Rob Norris Functional Programming with Effects Rob Norris @tpolecat the fish operator (Kleisli composition), can be implemented using flatMap. And this Fishy typeclass that we have derived from nothing, using math, is Monad. So this scary thing, it just comes naturally and I haven’t seen people talk about getting to it from this direction. And so I hope that was helpful. We can implement compose, the fish operator using flatMap, so the fish operator is something we can derive later really, the operation we need is flatMap. We can define a syntax class that adds these methods so that anything that is an F[A], if there is a Fishy instance, gets these operations by syntax.