SlideShare a Scribd company logo
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
@philip_schwarzslides by
Rob Norris
@tpolecat @BartoszMilewski
Bartosz Milewski Runar Bjarnason
@runarorama
Paul Chiusano
@pchiusano
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 leaned 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 ScalaRob Norris
@tpolecat@BartoszMilewski
Bartosz Milewski
Paul ChiusanoRunar 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 non-driver= Person(car=None)
val uninsured = Person(Some(Car(insurance=None)))
val insured = Person(Some(Car(Some(Insurance("Acme")))))
assert(carInsurance(non-driver).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'))
implicit class OptionFunctionOps[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
}
}
implicit class ListFunctionOps[A,B](f:A=>List[B] ) {
def >=>[C](g: B => List[C]): A => List[C] =
a => f(a).foldRight(List[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
@philip_schwarz
In the previous slide, it is the implicits OptionFunctionOps and ListFunctionOps
that are making available the fish operator >=> on functions whose codomain is a
List or an Option.
To see the fish operator and ordinary
function arrows in all their glory, select
the Fira Code font (e.g. in IntelliJ IDEA)
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.
implicit class OptionFunctionOps[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
}
}
implicit class ListFunctionOps[A, B](f: A => List[B] ) {
def >=>[C](g: B => List[C]): A => List[C] =
a => f(a).foldRight(List[C]())((b, cs) => g(b) ++ cs)
}
implicit class MonadFunctionOps[F[_], A, B](f: A => F[B] ) {
def >=>[C](g: B => F[C])(implicit M:Monad[F]): A => F[C] =
a => M.flatMap(f(a))(g)
}
trait Monad[F[_]] {
def unit[A](a: => A): F[A]
def flatMap[A, B](fa: F[A])(f: A => F[B]): F[B]
}
implicit val optionMonad = new Monad[Option] {
def unit[A](a: => A): Option[A] = Some(a)
def flatMap[A, B]
(fa: Option[A])(f: A => Option[B]): Option[B] = fa flatMap f
}
implicit val listMonad = new Monad[List] {
def unit[A](a: => A): List[A] = List(a)
def flatMap[A, B]
(fa: List[A])(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
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
@philip_schwarz
In the previous slides (and in future slides), where you see the implicits optionMonad, listMonad, and MonadFunctionOps,
here is how they work together to make available the fish operator >=> on functions whose codomain is a List or an Option.
Now let’s hand-code ourselves the flatMap
functions of the Option and List Monads.
implicit val optionMonad = new Monad[Option] {
def unit[A](a: => A): Option[A] =
Some(a)
def flatMap[A, B](fa:Option[A])(f: A => Option[B]):Option[B] =
fa flatMap f
}
implicit val listMonad = new Monad[List] {
def unit[A](a: => A): List[A] =
List(a)
def flatMap[A, B](fa:List[A])(f: A => List[B]):List[B] =
fa flatMap f
}
implicit val optionMonad = new Monad[Option] {
def unit[A](a: => A): Option[A] =
Some(a)
def flatMap[A, B](fa: Option[A])(f: A => Option[B]): Option[B] =
fa match {
case Some(a) => f(a)
case None => None
}
}
implicit val listMonad = new Monad[List] {
def unit[A](a: => A): List[A] =
List(a)
def flatMap[A, B](fa: List[A])(f: A => List[B]): List[B] =
fa.foldRight(List[B]())((a,bs) => f(a) ++ bs)
}
trait Monad[F[_]] { implicit class MonadFunctionOps[F[_], A, B](f: A => F[B] ) {
def unit[A](a: => A): F[A] def >=>[C](g: B => F[C])(implicit M:Monad[F]): A => F[C] =
def flatMap[A, B](fa: F[A])(f: A => F[B]): F[B] a => M.flatMap(f(a))(g)
} }
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 next 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
implicit val optionMonad = new Monad[Option] {
def unit[A](a: => A): Option[A] = Some(a)
def map[A, B](fa: Option[A])(f: A => B): Option[B] =
fa map f
def join[A](ffa: Option[Option[A]]): Option[A] =
ffa flatten
}
implicit val listMonad = new Monad[List] {
def unit[A](a: => A): List[A] = List(a)
def join[A](ffa: List[List[A]]): List[A] =
ffa flatten
def map[A, B](fa: List[A])(f: A => B): List[B] =
fa map f
}
Before After
>=> is generic and defined in terms of built-in flatMap >=> is generic and defined in terms of built-in map and join
implicit val optionMonad = new Monad[Option] {
def unit[A](a: => A): Option[A] = Some(a)
def flatMap[A, B](fa:Option[A])(f: A => Option[B]):Option[B] =
fa flatMap f
}
implicit val listMonad = new Monad[List] {
def unit[A](a: => A): List[A] = List(a)
def flatMap[A, B](fa:List[A])(f: A => List[B]):List[B] =
fa flatMap f
}
trait Functor[F[_]] {
def map[A, B](fa: F[A])(f: A => B): F[B]
}
trait Monad[F[_]] extends Functor[F] {
def unit[A](a: => A): F[A]
def join[A](ffa: F[F[A]]): F[A]
}
implicit class MonadFunctionOps[F[_], A, B](f: A => F[B] ) {
def >=>[C](g: B => F[C])(implicit M:Monad[F]): A => F[C] =
a => M.join(M.map(f(a))(g))
}
trait Monad[F[_]] {
def unit[A](a: => A): F[A]
def flatMap[A, B](fa: F[A])(f: A => F[B]): F[B]
}
implicit class MonadFunctionOps[F[_], A, B](f: A => F[B] ) {
def >=>[C](g: B => F[C])(implicit M:Monad[F]): A => F[C] =
a => M.flatMap(f(a))(g)
}
Now let’s hand-code ourselves the map and
join functions of the Option and List Monads.
implicit val optionMonad = new Monad[Option] {
def unit[A](a: => A): Option[A] = Some(a)
def map[A, B](fa: Option[A])(f: A => B): Option[B] = fa map f
def join[A](ffa: Option[Option[A]]): Option[A] = ffa flatten
}
implicit val listMonad = new Monad[List] {
def unit[A](a: => A): List[A] = List(a)
def map[A, B](fa: List[A])(f: A => B): List[B] = fa map f
def join[A](ffa: List[List[A]]): List[A] = ffa flatten
}
implicit val optionMonad = new Monad[Option] {
def unit[A](a: => A): Option[A] = Some(a)
def map[A, B](fa: Option[A])(f: A => B): Option[B] = fa match {
case Some(a) => Some(f(a))
case None => None
}
def join[A](ffa: Option[Option[A]]): Option[A] = ffa match {
case Some(a) => a
case None => None
}
}
implicit val listMonad = new Monad[List] {
def unit[A](a: => A): List[A] = List(a)
def map[A, B](fa: List[A])(f: A => B): List[B] = fa match {
case Nil => Nil
case head :: tail => f(head) :: map(tail)(f)
}
def join[A](ffa: List[List[A]]): List[A] = ffa match {
case Nil => Nil
case head :: tail => head ++ join(tail)
}
}
trait Functor[F[_]] {
def map[A,B](fa:F[A])(f:A =>B):F[B]
}
trait Monad[F[_]] extends Functor[F] {
def unit[A](a: => A):F[A]
def join[A](ffa:F[F[A]]):F[A]
}
implicit class MonadFunctionOps[F[_],A,B](f:A =>F[B]) {
def >=>[C](g:B=>F[C])(implicit M:Monad[F]):A =>F[C] =
a => M.join(M.map(f(a))(g))
}
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
Now a bonus slide: let’s hand-code again the
flatMap and join functions of List, but this time
without using built-ins foldRight and ++.
@philip_schwarz
implicit val listMonad = new Monad[List] {
def unit[A](a: => A): List[A] = List(a)
def map[A, B](fa: List[A])(f: A => B): List[B] = fa match {
case Nil => Nil
case head :: tail => f(head) :: map(tail)(f)
}
def join[A](ffa: List[List[A]]): List[A] = ffa match {
case Nil => Nil
case head :: tail => head ++ join(tail)
}
}
def concatenate[A](left: List[A], right: List[A]): List[A] =
left match {
case Nil => right
case head :: tail => head :: concatenate(tail, right)
}
implicit val listMonad = new Monad[List] {
def unit[A](a: => A): List[A] =
List(a)
def flatMap[A, B](fa: List[A])(f: A => List[B]): List[B] =
fa.foldRight(List[B]())((a,bs) => f(a) ++ bs)
}
Bonus Slide – hand-coding flatMap and join for List without using built-in foldRight and ++
def join[A](ffa: List[List[A]]): List[A] =
ffa match {
case Nil => Nil
case head :: tail => concatenate(head, join(tail))
}
def flatMap[A, B](fa: List[A])(f: A => List[B]): List[B] =
fa match {
case Nil => Nil
case head :: tail => concatenate(f(head), flatMap(tail)(f))
}
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

What's hot

Functors
FunctorsFunctors
Functors
Philip Schwarz
 
Monad Transformers - Part 1
Monad Transformers - Part 1Monad Transformers - Part 1
Monad Transformers - Part 1
Philip Schwarz
 
Scala collection methods flatMap and flatten are more powerful than monadic f...
Scala collection methods flatMap and flatten are more powerful than monadic f...Scala collection methods flatMap and flatten are more powerful than monadic f...
Scala collection methods flatMap and flatten are more powerful than monadic f...
Philip Schwarz
 
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
Hang Zhao
 
Fp in scala with adts
Fp in scala with adtsFp in scala with adts
Fp in scala with adts
Hang Zhao
 
Sequence and Traverse - Part 2
Sequence and Traverse - Part 2Sequence and Traverse - Part 2
Sequence and Traverse - Part 2
Philip Schwarz
 
Fp in scala part 1
Fp in scala part 1Fp in scala part 1
Fp in scala part 1
Hang Zhao
 
Functor Laws
Functor LawsFunctor Laws
Functor Laws
Philip Schwarz
 
Monad Fact #2
Monad Fact #2Monad Fact #2
Monad Fact #2
Philip Schwarz
 
Simple IO Monad in 'Functional Programming in Scala'
Simple IO Monad in 'Functional Programming in Scala'Simple IO Monad in 'Functional Programming in Scala'
Simple IO Monad in 'Functional Programming in Scala'
Philip Schwarz
 
Monoids - Part 1 - with examples using Scalaz and Cats
Monoids - Part 1 - with examples using Scalaz and CatsMonoids - Part 1 - with examples using Scalaz and Cats
Monoids - Part 1 - with examples using Scalaz and Cats
Philip Schwarz
 
Monad Fact #4
Monad Fact #4Monad Fact #4
Monad Fact #4
Philip Schwarz
 
Quicksort - a whistle-stop tour of the algorithm in five languages and four p...
Quicksort - a whistle-stop tour of the algorithm in five languages and four p...Quicksort - a whistle-stop tour of the algorithm in five languages and four p...
Quicksort - a whistle-stop tour of the algorithm in five languages and four p...
Philip Schwarz
 
Scala 3 enum for a terser Option Monad Algebraic Data Type
Scala 3 enum for a terser Option Monad Algebraic Data TypeScala 3 enum for a terser Option Monad Algebraic Data Type
Scala 3 enum for a terser Option Monad Algebraic Data Type
Philip Schwarz
 
Scala. Introduction to FP. Monads
Scala. Introduction to FP. MonadsScala. Introduction to FP. Monads
Scala. Introduction to FP. Monads
Kirill Kozlov
 
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part ...
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part ...Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part ...
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part ...
Philip Schwarz
 
Functional Core and Imperative Shell - Game of Life Example - Haskell and Scala
Functional Core and Imperative Shell - Game of Life Example - Haskell and ScalaFunctional Core and Imperative Shell - Game of Life Example - Haskell and Scala
Functional Core and Imperative Shell - Game of Life Example - Haskell and Scala
Philip Schwarz
 
N-Queens Combinatorial Problem - Polyglot FP for fun and profit - Haskell and...
N-Queens Combinatorial Problem - Polyglot FP for fun and profit - Haskell and...N-Queens Combinatorial Problem - Polyglot FP for fun and profit - Haskell and...
N-Queens Combinatorial Problem - Polyglot FP for fun and profit - Haskell and...
Philip Schwarz
 
Monad Laws Must be Checked
Monad Laws Must be CheckedMonad Laws Must be Checked
Monad Laws Must be Checked
Philip Schwarz
 
Introduction to Monads in Scala (2)
Introduction to Monads in Scala (2)Introduction to Monads in Scala (2)
Introduction to Monads in Scala (2)
stasimus
 

What's hot (20)

Functors
FunctorsFunctors
Functors
 
Monad Transformers - Part 1
Monad Transformers - Part 1Monad Transformers - Part 1
Monad Transformers - Part 1
 
Scala collection methods flatMap and flatten are more powerful than monadic f...
Scala collection methods flatMap and flatten are more powerful than monadic f...Scala collection methods flatMap and flatten are more powerful than monadic f...
Scala collection methods flatMap and flatten are more powerful than monadic f...
 
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
 
Fp in scala with adts
Fp in scala with adtsFp in scala with adts
Fp in scala with adts
 
Sequence and Traverse - Part 2
Sequence and Traverse - Part 2Sequence and Traverse - Part 2
Sequence and Traverse - Part 2
 
Fp in scala part 1
Fp in scala part 1Fp in scala part 1
Fp in scala part 1
 
Functor Laws
Functor LawsFunctor Laws
Functor Laws
 
Monad Fact #2
Monad Fact #2Monad Fact #2
Monad Fact #2
 
Simple IO Monad in 'Functional Programming in Scala'
Simple IO Monad in 'Functional Programming in Scala'Simple IO Monad in 'Functional Programming in Scala'
Simple IO Monad in 'Functional Programming in Scala'
 
Monoids - Part 1 - with examples using Scalaz and Cats
Monoids - Part 1 - with examples using Scalaz and CatsMonoids - Part 1 - with examples using Scalaz and Cats
Monoids - Part 1 - with examples using Scalaz and Cats
 
Monad Fact #4
Monad Fact #4Monad Fact #4
Monad Fact #4
 
Quicksort - a whistle-stop tour of the algorithm in five languages and four p...
Quicksort - a whistle-stop tour of the algorithm in five languages and four p...Quicksort - a whistle-stop tour of the algorithm in five languages and four p...
Quicksort - a whistle-stop tour of the algorithm in five languages and four p...
 
Scala 3 enum for a terser Option Monad Algebraic Data Type
Scala 3 enum for a terser Option Monad Algebraic Data TypeScala 3 enum for a terser Option Monad Algebraic Data Type
Scala 3 enum for a terser Option Monad Algebraic Data Type
 
Scala. Introduction to FP. Monads
Scala. Introduction to FP. MonadsScala. Introduction to FP. Monads
Scala. Introduction to FP. Monads
 
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part ...
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part ...Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part ...
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part ...
 
Functional Core and Imperative Shell - Game of Life Example - Haskell and Scala
Functional Core and Imperative Shell - Game of Life Example - Haskell and ScalaFunctional Core and Imperative Shell - Game of Life Example - Haskell and Scala
Functional Core and Imperative Shell - Game of Life Example - Haskell and Scala
 
N-Queens Combinatorial Problem - Polyglot FP for fun and profit - Haskell and...
N-Queens Combinatorial Problem - Polyglot FP for fun and profit - Haskell and...N-Queens Combinatorial Problem - Polyglot FP for fun and profit - Haskell and...
N-Queens Combinatorial Problem - Polyglot FP for fun and profit - Haskell and...
 
Monad Laws Must be Checked
Monad Laws Must be CheckedMonad Laws Must be Checked
Monad Laws Must be Checked
 
Introduction to Monads in Scala (2)
Introduction to Monads in Scala (2)Introduction to Monads in Scala (2)
Introduction to Monads in Scala (2)
 

Similar to Kleisli composition, flatMap, join, map, unit - implementation and interrelation

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...
Philip Schwarz
 
(2015 06-16) Three Approaches to Monads
(2015 06-16) Three Approaches to Monads(2015 06-16) Three Approaches to Monads
(2015 06-16) Three Approaches to Monads
Lawrence Evans
 
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
Luka Jacobowitz
 
Monads and friends demystified
Monads and friends demystifiedMonads and friends demystified
Monads and friends demystified
Alessandro Lacava
 
Monoids, Monoids, Monoids - ScalaLove 2020
Monoids, Monoids, Monoids - ScalaLove 2020Monoids, Monoids, Monoids - ScalaLove 2020
Monoids, Monoids, Monoids - ScalaLove 2020
Luka Jacobowitz
 
Algebraic Data Types and Origami Patterns
Algebraic Data Types and Origami PatternsAlgebraic Data Types and Origami Patterns
Algebraic Data Types and Origami Patterns
Vasil Remeniuk
 
From Function1#apply to Kleisli
From Function1#apply to KleisliFrom Function1#apply to Kleisli
From Function1#apply to Kleisli
Hermann Hueck
 
From Functor Composition to Monad Transformers
From Functor Composition to Monad TransformersFrom Functor Composition to Monad Transformers
From Functor Composition to Monad Transformers
Hermann Hueck
 
Monoids, monoids, monoids
Monoids, monoids, monoidsMonoids, monoids, monoids
Monoids, monoids, monoids
Luka Jacobowitz
 
Monad presentation scala as a category
Monad presentation   scala as a categoryMonad presentation   scala as a category
Monad presentation scala as a category
samthemonad
 
Monad as functor with pair of natural transformations
Monad as functor with pair of natural transformationsMonad as functor with pair of natural transformations
Monad as functor with pair of natural transformations
Philip Schwarz
 
Fp in scala part 2
Fp in scala part 2Fp in scala part 2
Fp in scala part 2
Hang Zhao
 
N-Queens Combinatorial Problem - Polyglot FP for Fun and Profit - Haskell and...
N-Queens Combinatorial Problem - Polyglot FP for Fun and Profit - Haskell and...N-Queens Combinatorial Problem - Polyglot FP for Fun and Profit - Haskell and...
N-Queens Combinatorial Problem - Polyglot FP for Fun and Profit - Haskell and...
Philip Schwarz
 
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
Ilan Godik
 
Monad and Algebraic Design in Functional Programming
Monad and Algebraic Design in Functional ProgrammingMonad and Algebraic Design in Functional Programming
Monad and Algebraic Design in Functional Programming
Namuk Park
 
Frp2016 3
Frp2016 3Frp2016 3
Frp2016 3
Kirill Kozlov
 
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 4
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 4Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 4
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 4
Philip Schwarz
 
Practical cats
Practical catsPractical cats
Practical cats
Raymond Tay
 
Running Free with the Monads
Running Free with the MonadsRunning Free with the Monads
Running Free with the Monads
kenbot
 
N-Queens Combinatorial Problem - Polyglot FP for Fun and Profit – Haskell and...
N-Queens Combinatorial Problem - Polyglot FP for Fun and Profit – Haskell and...N-Queens Combinatorial Problem - Polyglot FP for Fun and Profit – Haskell and...
N-Queens Combinatorial Problem - Polyglot FP for Fun and Profit – Haskell and...
Philip Schwarz
 

Similar to Kleisli composition, flatMap, join, map, unit - implementation and interrelation (20)

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...
 
(2015 06-16) Three Approaches to Monads
(2015 06-16) Three Approaches to Monads(2015 06-16) Three Approaches to Monads
(2015 06-16) Three Approaches to Monads
 
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
 
Monoids, Monoids, Monoids - ScalaLove 2020
Monoids, Monoids, Monoids - ScalaLove 2020Monoids, Monoids, Monoids - ScalaLove 2020
Monoids, Monoids, Monoids - ScalaLove 2020
 
Algebraic Data Types and Origami Patterns
Algebraic Data Types and Origami PatternsAlgebraic Data Types and Origami Patterns
Algebraic Data Types and Origami Patterns
 
From Function1#apply to Kleisli
From Function1#apply to KleisliFrom Function1#apply to Kleisli
From Function1#apply to Kleisli
 
From Functor Composition to Monad Transformers
From Functor Composition to Monad TransformersFrom Functor Composition to Monad Transformers
From Functor Composition to Monad Transformers
 
Monoids, monoids, monoids
Monoids, monoids, monoidsMonoids, monoids, monoids
Monoids, monoids, monoids
 
Monad presentation scala as a category
Monad presentation   scala as a categoryMonad presentation   scala as a category
Monad presentation scala as a category
 
Monad as functor with pair of natural transformations
Monad as functor with pair of natural transformationsMonad as functor with pair of natural transformations
Monad as functor with pair of natural transformations
 
Fp in scala part 2
Fp in scala part 2Fp in scala part 2
Fp in scala part 2
 
N-Queens Combinatorial Problem - Polyglot FP for Fun and Profit - Haskell and...
N-Queens Combinatorial Problem - Polyglot FP for Fun and Profit - Haskell and...N-Queens Combinatorial Problem - Polyglot FP for Fun and Profit - Haskell and...
N-Queens Combinatorial Problem - Polyglot FP for Fun and Profit - Haskell and...
 
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
 
Monad and Algebraic Design in Functional Programming
Monad and Algebraic Design in Functional ProgrammingMonad and Algebraic Design in Functional Programming
Monad and Algebraic Design in Functional Programming
 
Frp2016 3
Frp2016 3Frp2016 3
Frp2016 3
 
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 4
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 4Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 4
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 4
 
Practical cats
Practical catsPractical cats
Practical cats
 
Running Free with the Monads
Running Free with the MonadsRunning Free with the Monads
Running Free with the Monads
 
N-Queens Combinatorial Problem - Polyglot FP for Fun and Profit – Haskell and...
N-Queens Combinatorial Problem - Polyglot FP for Fun and Profit – Haskell and...N-Queens Combinatorial Problem - Polyglot FP for Fun and Profit – Haskell and...
N-Queens Combinatorial Problem - Polyglot FP for Fun and Profit – Haskell and...
 

More from Philip Schwarz

Hand Rolled Applicative User Validation Code Kata
Hand Rolled Applicative User ValidationCode KataHand Rolled Applicative User ValidationCode Kata
Hand Rolled Applicative User Validation Code Kata
Philip Schwarz
 
A Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of PassageA Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of Passage
Philip Schwarz
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
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 series
Philip 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 series
Philip 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 series
Philip 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 series
Philip Schwarz
 
Scala Left Fold Parallelisation - Three Approaches
Scala Left Fold Parallelisation- Three ApproachesScala Left Fold Parallelisation- Three Approaches
Scala Left Fold Parallelisation - Three Approaches
Philip 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 Programs
Philip 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 Views
Philip 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 Scala
Philip 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 Scala
Philip 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 Scala
Philip Schwarz
 
N-Queens Combinatorial Puzzle meets Cats
N-Queens Combinatorial Puzzle meets CatsN-Queens Combinatorial Puzzle meets Cats
N-Queens Combinatorial Puzzle meets Cats
Philip 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 example
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 example
Philip 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
 

More from Philip Schwarz (20)

Hand Rolled Applicative User Validation Code Kata
Hand Rolled Applicative User ValidationCode KataHand Rolled Applicative User ValidationCode Kata
Hand Rolled Applicative User Validation Code Kata
 
A Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of PassageA Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of Passage
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
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...
 

Recently uploaded

E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian CompaniesE-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
Quickdice ERP
 
UI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
UI5con 2024 - Boost Your Development Experience with UI5 Tooling ExtensionsUI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
UI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
Peter Muessig
 
Oracle 23c New Features For DBAs and Developers.pptx
Oracle 23c New Features For DBAs and Developers.pptxOracle 23c New Features For DBAs and Developers.pptx
Oracle 23c New Features For DBAs and Developers.pptx
Remote DBA Services
 
Odoo ERP Vs. Traditional ERP Systems – A Comparative Analysis
Odoo ERP Vs. Traditional ERP Systems – A Comparative AnalysisOdoo ERP Vs. Traditional ERP Systems – A Comparative Analysis
Odoo ERP Vs. Traditional ERP Systems – A Comparative Analysis
Envertis Software Solutions
 
Fundamentals of Programming and Language Processors
Fundamentals of Programming and Language ProcessorsFundamentals of Programming and Language Processors
Fundamentals of Programming and Language Processors
Rakesh Kumar R
 
Top Benefits of Using Salesforce Healthcare CRM for Patient Management.pdf
Top Benefits of Using Salesforce Healthcare CRM for Patient Management.pdfTop Benefits of Using Salesforce Healthcare CRM for Patient Management.pdf
Top Benefits of Using Salesforce Healthcare CRM for Patient Management.pdf
VALiNTRY360
 
Unveiling the Advantages of Agile Software Development.pdf
Unveiling the Advantages of Agile Software Development.pdfUnveiling the Advantages of Agile Software Development.pdf
Unveiling the Advantages of Agile Software Development.pdf
brainerhub1
 
原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
mz5nrf0n
 
SMS API Integration in Saudi Arabia| Best SMS API Service
SMS API Integration in Saudi Arabia| Best SMS API ServiceSMS API Integration in Saudi Arabia| Best SMS API Service
SMS API Integration in Saudi Arabia| Best SMS API Service
Yara Milbes
 
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CDKuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
rodomar2
 
GreenCode-A-VSCode-Plugin--Dario-Jurisic
GreenCode-A-VSCode-Plugin--Dario-JurisicGreenCode-A-VSCode-Plugin--Dario-Jurisic
GreenCode-A-VSCode-Plugin--Dario-Jurisic
Green Software Development
 
Using Query Store in Azure PostgreSQL to Understand Query Performance
Using Query Store in Azure PostgreSQL to Understand Query PerformanceUsing Query Store in Azure PostgreSQL to Understand Query Performance
Using Query Store in Azure PostgreSQL to Understand Query Performance
Grant Fritchey
 
Modelling Up - DDDEurope 2024 - Amsterdam
Modelling Up - DDDEurope 2024 - AmsterdamModelling Up - DDDEurope 2024 - Amsterdam
Modelling Up - DDDEurope 2024 - Amsterdam
Alberto Brandolini
 
How Can Hiring A Mobile App Development Company Help Your Business Grow?
How Can Hiring A Mobile App Development Company Help Your Business Grow?How Can Hiring A Mobile App Development Company Help Your Business Grow?
How Can Hiring A Mobile App Development Company Help Your Business Grow?
ToXSL Technologies
 
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Łukasz Chruściel
 
Oracle Database 19c New Features for DBAs and Developers.pptx
Oracle Database 19c New Features for DBAs and Developers.pptxOracle Database 19c New Features for DBAs and Developers.pptx
Oracle Database 19c New Features for DBAs and Developers.pptx
Remote DBA Services
 
Lecture 2 - software testing SE 412.pptx
Lecture 2 - software testing SE 412.pptxLecture 2 - software testing SE 412.pptx
Lecture 2 - software testing SE 412.pptx
TaghreedAltamimi
 
How to write a program in any programming language
How to write a program in any programming languageHow to write a program in any programming language
How to write a program in any programming language
Rakesh Kumar R
 
Energy consumption of Database Management - Florina Jonuzi
Energy consumption of Database Management - Florina JonuziEnergy consumption of Database Management - Florina Jonuzi
Energy consumption of Database Management - Florina Jonuzi
Green Software Development
 
Measures in SQL (SIGMOD 2024, Santiago, Chile)
Measures in SQL (SIGMOD 2024, Santiago, Chile)Measures in SQL (SIGMOD 2024, Santiago, Chile)
Measures in SQL (SIGMOD 2024, Santiago, Chile)
Julian Hyde
 

Recently uploaded (20)

E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian CompaniesE-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
 
UI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
UI5con 2024 - Boost Your Development Experience with UI5 Tooling ExtensionsUI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
UI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
 
Oracle 23c New Features For DBAs and Developers.pptx
Oracle 23c New Features For DBAs and Developers.pptxOracle 23c New Features For DBAs and Developers.pptx
Oracle 23c New Features For DBAs and Developers.pptx
 
Odoo ERP Vs. Traditional ERP Systems – A Comparative Analysis
Odoo ERP Vs. Traditional ERP Systems – A Comparative AnalysisOdoo ERP Vs. Traditional ERP Systems – A Comparative Analysis
Odoo ERP Vs. Traditional ERP Systems – A Comparative Analysis
 
Fundamentals of Programming and Language Processors
Fundamentals of Programming and Language ProcessorsFundamentals of Programming and Language Processors
Fundamentals of Programming and Language Processors
 
Top Benefits of Using Salesforce Healthcare CRM for Patient Management.pdf
Top Benefits of Using Salesforce Healthcare CRM for Patient Management.pdfTop Benefits of Using Salesforce Healthcare CRM for Patient Management.pdf
Top Benefits of Using Salesforce Healthcare CRM for Patient Management.pdf
 
Unveiling the Advantages of Agile Software Development.pdf
Unveiling the Advantages of Agile Software Development.pdfUnveiling the Advantages of Agile Software Development.pdf
Unveiling the Advantages of Agile Software Development.pdf
 
原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
 
SMS API Integration in Saudi Arabia| Best SMS API Service
SMS API Integration in Saudi Arabia| Best SMS API ServiceSMS API Integration in Saudi Arabia| Best SMS API Service
SMS API Integration in Saudi Arabia| Best SMS API Service
 
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CDKuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
 
GreenCode-A-VSCode-Plugin--Dario-Jurisic
GreenCode-A-VSCode-Plugin--Dario-JurisicGreenCode-A-VSCode-Plugin--Dario-Jurisic
GreenCode-A-VSCode-Plugin--Dario-Jurisic
 
Using Query Store in Azure PostgreSQL to Understand Query Performance
Using Query Store in Azure PostgreSQL to Understand Query PerformanceUsing Query Store in Azure PostgreSQL to Understand Query Performance
Using Query Store in Azure PostgreSQL to Understand Query Performance
 
Modelling Up - DDDEurope 2024 - Amsterdam
Modelling Up - DDDEurope 2024 - AmsterdamModelling Up - DDDEurope 2024 - Amsterdam
Modelling Up - DDDEurope 2024 - Amsterdam
 
How Can Hiring A Mobile App Development Company Help Your Business Grow?
How Can Hiring A Mobile App Development Company Help Your Business Grow?How Can Hiring A Mobile App Development Company Help Your Business Grow?
How Can Hiring A Mobile App Development Company Help Your Business Grow?
 
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
 
Oracle Database 19c New Features for DBAs and Developers.pptx
Oracle Database 19c New Features for DBAs and Developers.pptxOracle Database 19c New Features for DBAs and Developers.pptx
Oracle Database 19c New Features for DBAs and Developers.pptx
 
Lecture 2 - software testing SE 412.pptx
Lecture 2 - software testing SE 412.pptxLecture 2 - software testing SE 412.pptx
Lecture 2 - software testing SE 412.pptx
 
How to write a program in any programming language
How to write a program in any programming languageHow to write a program in any programming language
How to write a program in any programming language
 
Energy consumption of Database Management - Florina Jonuzi
Energy consumption of Database Management - Florina JonuziEnergy consumption of Database Management - Florina Jonuzi
Energy consumption of Database Management - Florina Jonuzi
 
Measures in SQL (SIGMOD 2024, Santiago, Chile)
Measures in SQL (SIGMOD 2024, Santiago, Chile)Measures in SQL (SIGMOD 2024, Santiago, Chile)
Measures in SQL (SIGMOD 2024, Santiago, Chile)
 

Kleisli composition, flatMap, join, map, unit - implementation and interrelation

  • 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 @philip_schwarzslides by Rob Norris @tpolecat @BartoszMilewski Bartosz Milewski Runar Bjarnason @runarorama Paul Chiusano @pchiusano
  • 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 leaned 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 ScalaRob Norris @tpolecat@BartoszMilewski Bartosz Milewski Paul ChiusanoRunar 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 non-driver= Person(car=None) val uninsured = Person(Some(Car(insurance=None))) val insured = Person(Some(Car(Some(Insurance("Acme"))))) assert(carInsurance(non-driver).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')) implicit class OptionFunctionOps[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 } } implicit class ListFunctionOps[A,B](f:A=>List[B] ) { def >=>[C](g: B => List[C]): A => List[C] = a => f(a).foldRight(List[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. @philip_schwarz In the previous slide, it is the implicits OptionFunctionOps and ListFunctionOps that are making available the fish operator >=> on functions whose codomain is a List or an Option. To see the fish operator and ordinary function arrows in all their glory, select the Fira Code font (e.g. in IntelliJ IDEA)
  • 5. 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.
  • 6. implicit class OptionFunctionOps[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 } } implicit class ListFunctionOps[A, B](f: A => List[B] ) { def >=>[C](g: B => List[C]): A => List[C] = a => f(a).foldRight(List[C]())((b, cs) => g(b) ++ cs) } implicit class MonadFunctionOps[F[_], A, B](f: A => F[B] ) { def >=>[C](g: B => F[C])(implicit M:Monad[F]): A => F[C] = a => M.flatMap(f(a))(g) } trait Monad[F[_]] { def unit[A](a: => A): F[A] def flatMap[A, B](fa: F[A])(f: A => F[B]): F[B] } implicit val optionMonad = new Monad[Option] { def unit[A](a: => A): Option[A] = Some(a) def flatMap[A, B] (fa: Option[A])(f: A => Option[B]): Option[B] = fa flatMap f } implicit val listMonad = new Monad[List] { def unit[A](a: => A): List[A] = List(a) def flatMap[A, B] (fa: List[A])(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
  • 7. 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
  • 8. 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
  • 9. @philip_schwarz In the previous slides (and in future slides), where you see the implicits optionMonad, listMonad, and MonadFunctionOps, here is how they work together to make available the fish operator >=> on functions whose codomain is a List or an Option.
  • 10. Now let’s hand-code ourselves the flatMap functions of the Option and List Monads.
  • 11. implicit val optionMonad = new Monad[Option] { def unit[A](a: => A): Option[A] = Some(a) def flatMap[A, B](fa:Option[A])(f: A => Option[B]):Option[B] = fa flatMap f } implicit val listMonad = new Monad[List] { def unit[A](a: => A): List[A] = List(a) def flatMap[A, B](fa:List[A])(f: A => List[B]):List[B] = fa flatMap f } implicit val optionMonad = new Monad[Option] { def unit[A](a: => A): Option[A] = Some(a) def flatMap[A, B](fa: Option[A])(f: A => Option[B]): Option[B] = fa match { case Some(a) => f(a) case None => None } } implicit val listMonad = new Monad[List] { def unit[A](a: => A): List[A] = List(a) def flatMap[A, B](fa: List[A])(f: A => List[B]): List[B] = fa.foldRight(List[B]())((a,bs) => f(a) ++ bs) } trait Monad[F[_]] { implicit class MonadFunctionOps[F[_], A, B](f: A => F[B] ) { def unit[A](a: => A): F[A] def >=>[C](g: B => F[C])(implicit M:Monad[F]): A => F[C] = def flatMap[A, B](fa: F[A])(f: A => F[B]): F[B] a => M.flatMap(f(a))(g) } } Before After >=> is generic and defined in terms of built-in flatMap >=> is generic and defined in terms of hand-coded flatMap
  • 12. 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 next slide.
  • 13. 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
  • 14. implicit val optionMonad = new Monad[Option] { def unit[A](a: => A): Option[A] = Some(a) def map[A, B](fa: Option[A])(f: A => B): Option[B] = fa map f def join[A](ffa: Option[Option[A]]): Option[A] = ffa flatten } implicit val listMonad = new Monad[List] { def unit[A](a: => A): List[A] = List(a) def join[A](ffa: List[List[A]]): List[A] = ffa flatten def map[A, B](fa: List[A])(f: A => B): List[B] = fa map f } Before After >=> is generic and defined in terms of built-in flatMap >=> is generic and defined in terms of built-in map and join implicit val optionMonad = new Monad[Option] { def unit[A](a: => A): Option[A] = Some(a) def flatMap[A, B](fa:Option[A])(f: A => Option[B]):Option[B] = fa flatMap f } implicit val listMonad = new Monad[List] { def unit[A](a: => A): List[A] = List(a) def flatMap[A, B](fa:List[A])(f: A => List[B]):List[B] = fa flatMap f } trait Functor[F[_]] { def map[A, B](fa: F[A])(f: A => B): F[B] } trait Monad[F[_]] extends Functor[F] { def unit[A](a: => A): F[A] def join[A](ffa: F[F[A]]): F[A] } implicit class MonadFunctionOps[F[_], A, B](f: A => F[B] ) { def >=>[C](g: B => F[C])(implicit M:Monad[F]): A => F[C] = a => M.join(M.map(f(a))(g)) } trait Monad[F[_]] { def unit[A](a: => A): F[A] def flatMap[A, B](fa: F[A])(f: A => F[B]): F[B] } implicit class MonadFunctionOps[F[_], A, B](f: A => F[B] ) { def >=>[C](g: B => F[C])(implicit M:Monad[F]): A => F[C] = a => M.flatMap(f(a))(g) }
  • 15. Now let’s hand-code ourselves the map and join functions of the Option and List Monads.
  • 16. implicit val optionMonad = new Monad[Option] { def unit[A](a: => A): Option[A] = Some(a) def map[A, B](fa: Option[A])(f: A => B): Option[B] = fa map f def join[A](ffa: Option[Option[A]]): Option[A] = ffa flatten } implicit val listMonad = new Monad[List] { def unit[A](a: => A): List[A] = List(a) def map[A, B](fa: List[A])(f: A => B): List[B] = fa map f def join[A](ffa: List[List[A]]): List[A] = ffa flatten } implicit val optionMonad = new Monad[Option] { def unit[A](a: => A): Option[A] = Some(a) def map[A, B](fa: Option[A])(f: A => B): Option[B] = fa match { case Some(a) => Some(f(a)) case None => None } def join[A](ffa: Option[Option[A]]): Option[A] = ffa match { case Some(a) => a case None => None } } implicit val listMonad = new Monad[List] { def unit[A](a: => A): List[A] = List(a) def map[A, B](fa: List[A])(f: A => B): List[B] = fa match { case Nil => Nil case head :: tail => f(head) :: map(tail)(f) } def join[A](ffa: List[List[A]]): List[A] = ffa match { case Nil => Nil case head :: tail => head ++ join(tail) } } trait Functor[F[_]] { def map[A,B](fa:F[A])(f:A =>B):F[B] } trait Monad[F[_]] extends Functor[F] { def unit[A](a: => A):F[A] def join[A](ffa:F[F[A]]):F[A] } implicit class MonadFunctionOps[F[_],A,B](f:A =>F[B]) { def >=>[C](g:B=>F[C])(implicit M:Monad[F]):A =>F[C] = a => M.join(M.map(f(a))(g)) } 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
  • 17. Now a bonus slide: let’s hand-code again the flatMap and join functions of List, but this time without using built-ins foldRight and ++. @philip_schwarz
  • 18. implicit val listMonad = new Monad[List] { def unit[A](a: => A): List[A] = List(a) def map[A, B](fa: List[A])(f: A => B): List[B] = fa match { case Nil => Nil case head :: tail => f(head) :: map(tail)(f) } def join[A](ffa: List[List[A]]): List[A] = ffa match { case Nil => Nil case head :: tail => head ++ join(tail) } } def concatenate[A](left: List[A], right: List[A]): List[A] = left match { case Nil => right case head :: tail => head :: concatenate(tail, right) } implicit val listMonad = new Monad[List] { def unit[A](a: => A): List[A] = List(a) def flatMap[A, B](fa: List[A])(f: A => List[B]): List[B] = fa.foldRight(List[B]())((a,bs) => f(a) ++ bs) } Bonus Slide – hand-coding flatMap and join for List without using built-in foldRight and ++ def join[A](ffa: List[List[A]]): List[A] = ffa match { case Nil => Nil case head :: tail => concatenate(head, join(tail)) } def flatMap[A, B](fa: List[A])(f: A => List[B]): List[B] = fa match { case Nil => Nil case head :: tail => concatenate(f(head), flatMap(tail)(f)) }
  • 19. 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.
  • 20. 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.