SlideShare ist ein Scribd-Unternehmen logo
1 von 8
Downloaden Sie, um offline zu lesen
MONAD FACT #1
Scala for comprehensions require a monad to be defined in terms of
unit, map and flatMap rather than simply in terms of unit and flatMap
@philip_schwarzslides by
https://www.slideshare.net/pjschwarz
sealed trait Option[+A]
case object None extends Option[Nothing]
case class Some[+A](get: A) extends Option[A]
trait Monad[F[_]] {
def flatMap[A,B](ma: F[A])(f: A => F[B]): F[B]
def unit[A](a: => A): F[A]
}
val optionMonad = new Monad[Option] {
def unit[A](a: => A): Option[A] = Some(a)
def flatMap[A, B](ma: Option[A])(f: A => Option[B]): Option[B] = {
ma match {
case Some(a) => f(a)
case None => None
}
}
}
One way to define a monad is with the following trait
@philip_schwarz
If we define a data structure, e.g. an Option
we can then create a monad instance for Option by providing implementations for unit and flatMap
def greeting(maybeGreeting: Option[String],
maybeName: Option[String],
maybeSurname: Option[String]): Option[String] =
optionMonad.flatMap(maybeGreeting) { greeting =>
optionMonad.flatMap(maybeName) { name =>
optionMonad.flatMap(maybeSurname) { surname =>
optionMonad.unit(s"$greeting $name $surname!")
}
}
}
assert(
greeting(maybeGreeting = Some("Hello"), maybeName = Some("Fred"), maybeSurname = Some("Smith"))
== Some("Hello Fred Smith!"))
assert(
greeting(maybeGreeting = Some("Hello"), maybeName = None, maybeSurname = Some("Smith"))
== None)
Here is an example of using the Option monad instance
We just saw how to define the Option monad by defining unit and
flatMap functions that operate on Option.
Another way of defining the Option monad is by adding map and
flatMap functions to Option.
@philip_schwarz
If we do that, then we can take advantage of a
great Scala feature that allows code that uses the
monad to be much easier to understand than
woud otherwise be the case. Here is how the
greeting example looks like using this feature.
sealed trait Option[+A] {
def map[B](f: A => B): Option[B] =
this match {
case None => None
case Some(a) => Some(f(a))
}
def flatMap[B](f: A => Option[B]): Option[B] =
this match {
case None => None
case Some(a) => f(a)
}
}
case object None extends Option[Nothing]
case class Some[+A](get: A) extends Option[A]
def greeting(maybeGreeting: Option[String],
maybeName: Option[String],
maybeSurname: Option[String]): Option[String] =
for {
greeting <- maybeGreeting
name <- maybeName
surname <- maybeSurname
} yield s"$greeting $name $surname!"
assert(greeting(maybeGreeting = Some("Hello"), maybeName = Some("Fred"), maybeSurname = Some("Smith"))
== Some("Hello Fred Smith!"))
assert(greeting(maybeGreeting = Some("Hello"), maybeName = None, maybeSurname = Some("Smith"))
== None)
The feature in question is the ability to write an easy-to-understand for comprehension,
whose syntactic sugar is translated by the Scala compiler into a harder-to-understand
desugared chain of calls to map and flatMap
maybeGreeting flatMap { greeting =>
maybeName flatMap { name =>
maybeSurname map { surname =>
s"$greeting $name $surname!"
}
}
}
for {
greeting <- maybeGreeting
name <- maybeName
surname <- maybeSurname
} yield s"$greeting $name $surname!” desugars to
So why is it that in the first approach we can simply define a monad in terms of unit and flatMap
whereas in the second approach we have to define a monad in terms of unit, map and flatMap?
def map[B](f: A => B): Option[B] =
def flatMap[B](f: A => Option[B]): Option[B] =
case class Some[+A](get: A) extends Option[A] // Some acts as unit function
def flatMap[A,B](ma: F[A])(f: A => F[B]): F[B]
def unit[A](a: => A): F[A]
On the first slide we defined a monad simply in terms of unit and flatMap.
Later on, in order to take advantage of for comprehensions, we redefined a monad in terms of unit, map and
flatMap. “We did not define a unit function!”, I hear you say. Well, although it is not called unit, we did define it:
it is called Some, because creating a ‘defined’ Option, e.g. one with a value of 5, is done by evaluating Some(5)
(to get hold of the ‘undefined’ Option we use None).
@philip_schwarz
The answer to that question is that is that in Scala there is no Monad trait that monads can implement and that the compiler is
aware of, so the compiler does not know what the unit function of a monad is because for one thing, the function can have an
arbitrary name. In this case the unit function is called Some, in the case of the Either monad it is called Right, in the case of the List
monad it is called List, etc.
If there were some convention by which the compiler could figure out what the unit function of a monad is, then rather than
desugaring a for comprehension as follows:
It could desugar it to something like this:
maybeGreeting flatMap { greeting =>
maybeName flatMap { name =>
maybeSurname map { surname =>
s"$greeting $name $surname!"
}
}
}
for {
greeting <- maybeGreeting
name <- maybeName
surname <- maybeSurname
} yield s"$greeting $name $surname!” desugars to
maybeGreeting flatMap { greeting =>
maybeName flatMap { name =>
maybeSurname flatMap { surname =>
monadInstance.unit(s"$greeting $name $surname!")
}
}
}
maybeGreeting flatMap { greeting =>
maybeName flatMap { name =>
maybeSurname flatMap { surname =>
Some(s"$greeting $name $surname!")
}
}
}
See the following for the list of all available slide decks in the MONAD FACT series
https://www.slideshare.net/pjschwarz/the-monad-fact-slide-deck-series

Weitere Àhnliche Inhalte

Mehr von 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 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
 
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
 
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
 
The Sieve of Eratosthenes - Part 1 - with minor corrections
The Sieve of Eratosthenes - Part 1 - with minor correctionsThe Sieve of Eratosthenes - Part 1 - with minor corrections
The Sieve of Eratosthenes - Part 1 - with minor correctionsPhilip Schwarz
 
The Sieve of Eratosthenes - Part 1
The Sieve of Eratosthenes - Part 1The Sieve of Eratosthenes - Part 1
The Sieve of Eratosthenes - Part 1Philip Schwarz
 
The Uniform Access Principle
The Uniform Access PrincipleThe Uniform Access Principle
The Uniform Access PrinciplePhilip Schwarz
 
Computer Graphics in Java and Scala - Part 1b
Computer Graphics in Java and Scala - Part 1bComputer Graphics in Java and Scala - Part 1b
Computer Graphics in Java and Scala - Part 1bPhilip Schwarz
 
The Expression Problem - Part 2
The Expression Problem - Part 2The Expression Problem - Part 2
The Expression Problem - Part 2Philip Schwarz
 
Computer Graphics in Java and Scala - Part 1
Computer Graphics in Java and Scala - Part 1Computer Graphics in Java and Scala - Part 1
Computer Graphics in Java and Scala - Part 1Philip Schwarz
 

Mehr von Philip Schwarz (20)

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
 
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...
 
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 (...
 
The Sieve of Eratosthenes - Part 1 - with minor corrections
The Sieve of Eratosthenes - Part 1 - with minor correctionsThe Sieve of Eratosthenes - Part 1 - with minor corrections
The Sieve of Eratosthenes - Part 1 - with minor corrections
 
The Sieve of Eratosthenes - Part 1
The Sieve of Eratosthenes - Part 1The Sieve of Eratosthenes - Part 1
The Sieve of Eratosthenes - Part 1
 
The Uniform Access Principle
The Uniform Access PrincipleThe Uniform Access Principle
The Uniform Access Principle
 
Computer Graphics in Java and Scala - Part 1b
Computer Graphics in Java and Scala - Part 1bComputer Graphics in Java and Scala - Part 1b
Computer Graphics in Java and Scala - Part 1b
 
The Expression Problem - Part 2
The Expression Problem - Part 2The Expression Problem - Part 2
The Expression Problem - Part 2
 
Computer Graphics in Java and Scala - Part 1
Computer Graphics in Java and Scala - Part 1Computer Graphics in Java and Scala - Part 1
Computer Graphics in Java and Scala - Part 1
 

KĂŒrzlich hochgeladen

Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
call girls in Vaishali (Ghaziabad) 🔝 >àŒ’8448380779 🔝 genuine Escort Service đŸ”âœ”ïžâœ”ïž
call girls in Vaishali (Ghaziabad) 🔝 >àŒ’8448380779 🔝 genuine Escort Service đŸ”âœ”ïžâœ”ïžcall girls in Vaishali (Ghaziabad) 🔝 >àŒ’8448380779 🔝 genuine Escort Service đŸ”âœ”ïžâœ”ïž
call girls in Vaishali (Ghaziabad) 🔝 >àŒ’8448380779 🔝 genuine Escort Service đŸ”âœ”ïžâœ”ïžDelhi Call girls
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto GonzĂĄlez Trastoy
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
CALL ON ➄8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➄8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➄8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➄8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceanilsa9823
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
CALL ON ➄8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂
CALL ON ➄8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂CALL ON ➄8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂
CALL ON ➄8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂anilsa9823
 

KĂŒrzlich hochgeladen (20)

Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
call girls in Vaishali (Ghaziabad) 🔝 >àŒ’8448380779 🔝 genuine Escort Service đŸ”âœ”ïžâœ”ïž
call girls in Vaishali (Ghaziabad) 🔝 >àŒ’8448380779 🔝 genuine Escort Service đŸ”âœ”ïžâœ”ïžcall girls in Vaishali (Ghaziabad) 🔝 >àŒ’8448380779 🔝 genuine Escort Service đŸ”âœ”ïžâœ”ïž
call girls in Vaishali (Ghaziabad) 🔝 >àŒ’8448380779 🔝 genuine Escort Service đŸ”âœ”ïžâœ”ïž
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
CALL ON ➄8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➄8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➄8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➄8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
CALL ON ➄8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂
CALL ON ➄8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂CALL ON ➄8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂
CALL ON ➄8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂
 

Monad Fact #1

  • 1. MONAD FACT #1 Scala for comprehensions require a monad to be defined in terms of unit, map and flatMap rather than simply in terms of unit and flatMap @philip_schwarzslides by https://www.slideshare.net/pjschwarz
  • 2. sealed trait Option[+A] case object None extends Option[Nothing] case class Some[+A](get: A) extends Option[A] trait Monad[F[_]] { def flatMap[A,B](ma: F[A])(f: A => F[B]): F[B] def unit[A](a: => A): F[A] } val optionMonad = new Monad[Option] { def unit[A](a: => A): Option[A] = Some(a) def flatMap[A, B](ma: Option[A])(f: A => Option[B]): Option[B] = { ma match { case Some(a) => f(a) case None => None } } } One way to define a monad is with the following trait @philip_schwarz If we define a data structure, e.g. an Option we can then create a monad instance for Option by providing implementations for unit and flatMap
  • 3. def greeting(maybeGreeting: Option[String], maybeName: Option[String], maybeSurname: Option[String]): Option[String] = optionMonad.flatMap(maybeGreeting) { greeting => optionMonad.flatMap(maybeName) { name => optionMonad.flatMap(maybeSurname) { surname => optionMonad.unit(s"$greeting $name $surname!") } } } assert( greeting(maybeGreeting = Some("Hello"), maybeName = Some("Fred"), maybeSurname = Some("Smith")) == Some("Hello Fred Smith!")) assert( greeting(maybeGreeting = Some("Hello"), maybeName = None, maybeSurname = Some("Smith")) == None) Here is an example of using the Option monad instance
  • 4. We just saw how to define the Option monad by defining unit and flatMap functions that operate on Option. Another way of defining the Option monad is by adding map and flatMap functions to Option. @philip_schwarz If we do that, then we can take advantage of a great Scala feature that allows code that uses the monad to be much easier to understand than woud otherwise be the case. Here is how the greeting example looks like using this feature. sealed trait Option[+A] { def map[B](f: A => B): Option[B] = this match { case None => None case Some(a) => Some(f(a)) } def flatMap[B](f: A => Option[B]): Option[B] = this match { case None => None case Some(a) => f(a) } } case object None extends Option[Nothing] case class Some[+A](get: A) extends Option[A] def greeting(maybeGreeting: Option[String], maybeName: Option[String], maybeSurname: Option[String]): Option[String] = for { greeting <- maybeGreeting name <- maybeName surname <- maybeSurname } yield s"$greeting $name $surname!" assert(greeting(maybeGreeting = Some("Hello"), maybeName = Some("Fred"), maybeSurname = Some("Smith")) == Some("Hello Fred Smith!")) assert(greeting(maybeGreeting = Some("Hello"), maybeName = None, maybeSurname = Some("Smith")) == None)
  • 5. The feature in question is the ability to write an easy-to-understand for comprehension, whose syntactic sugar is translated by the Scala compiler into a harder-to-understand desugared chain of calls to map and flatMap maybeGreeting flatMap { greeting => maybeName flatMap { name => maybeSurname map { surname => s"$greeting $name $surname!" } } } for { greeting <- maybeGreeting name <- maybeName surname <- maybeSurname } yield s"$greeting $name $surname!” desugars to
  • 6. So why is it that in the first approach we can simply define a monad in terms of unit and flatMap whereas in the second approach we have to define a monad in terms of unit, map and flatMap? def map[B](f: A => B): Option[B] = def flatMap[B](f: A => Option[B]): Option[B] = case class Some[+A](get: A) extends Option[A] // Some acts as unit function def flatMap[A,B](ma: F[A])(f: A => F[B]): F[B] def unit[A](a: => A): F[A] On the first slide we defined a monad simply in terms of unit and flatMap. Later on, in order to take advantage of for comprehensions, we redefined a monad in terms of unit, map and flatMap. “We did not define a unit function!”, I hear you say. Well, although it is not called unit, we did define it: it is called Some, because creating a ‘defined’ Option, e.g. one with a value of 5, is done by evaluating Some(5) (to get hold of the ‘undefined’ Option we use None). @philip_schwarz
  • 7. The answer to that question is that is that in Scala there is no Monad trait that monads can implement and that the compiler is aware of, so the compiler does not know what the unit function of a monad is because for one thing, the function can have an arbitrary name. In this case the unit function is called Some, in the case of the Either monad it is called Right, in the case of the List monad it is called List, etc. If there were some convention by which the compiler could figure out what the unit function of a monad is, then rather than desugaring a for comprehension as follows: It could desugar it to something like this: maybeGreeting flatMap { greeting => maybeName flatMap { name => maybeSurname map { surname => s"$greeting $name $surname!" } } } for { greeting <- maybeGreeting name <- maybeName surname <- maybeSurname } yield s"$greeting $name $surname!” desugars to maybeGreeting flatMap { greeting => maybeName flatMap { name => maybeSurname flatMap { surname => monadInstance.unit(s"$greeting $name $surname!") } } } maybeGreeting flatMap { greeting => maybeName flatMap { name => maybeSurname flatMap { surname => Some(s"$greeting $name $surname!") } } }
  • 8. See the following for the list of all available slide decks in the MONAD FACT series https://www.slideshare.net/pjschwarz/the-monad-fact-slide-deck-series