SlideShare une entreprise Scribd logo
1  sur  23
Grokking Monads in Scala St. Louis Lambda Lounge August 5, 2010 Tim Dalton Senior Software Engineer Object Computing Inc.
Monads Are… Just a monoid in the category of endofunctors.  Like “duh”!
Monads Are… ,[object Object],[object Object],[object Object]
Monads Are… ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Haskell Monads ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Scala &quot;For comprehensions&quot; for (i <- 1 to 5) yield i scala.collection.immutable.IndexedSeq[Int] = Vector(1, 2, 3, 4, 5) for (i <- 1 to 5 if i % 2 == 0) yield i scala.collection.immutable.IndexedSeq[Int] = Vector(2, 4) for (i <-1 to 5 if i % 2 == 0) { print (i + &quot; &quot; ) } 2 4 for (i <-1 to 5 if i % 2 == 0; j <- 1 to 5 if j % 2 != 0) yield ( i * j ) scala.collection.immutable.IndexedSeq[Int] = Vector(2, 6, 10, 4, 12, 20) for (i <-1 to 5 if i % 2 == 0; j <- 1 to 5 if j % 2 != 0; k <- 1 to 5) yield ( i * j / k ) scala.collection.immutable.IndexedSeq[Int] = Vector(2, 1, 0, 0, 0, 6, 3, 2, 1, 1, 10, 5, 3, 2, 2, 4, 2, 1, 1, 0, 12, 6, 4, 3, 2, 20, 10, 6, 5, 4)
De-sugarized For comprehensions (1 to 5).map(identity) scala.collection.immutable.IndexedSeq[Int] = Vector(1, 2, 3, 4, 5) (1 to 5).filter{_ % 2 == 0}.map(identity) scala.collection.immutable.IndexedSeq[Int] = Vector(2, 4) (1 to 5).filter{_ % 2 == 0}.foreach { i => print (i + &quot; &quot; ) } 2 4 (1 to 5).filter{_ % 2 == 0}.flatMap { i => (1 to 5).filter{_ % 2 != 0}.map{ j  => i * j }  } scala.collection.immutable.IndexedSeq[Int] = Vector(2, 6, 10, 4, 12, 20) (1 to 5).filter{_ % 2 == 0}.flatMap { i => (1 to 5).filter{_ % 2 != 0}.flatMap{ j => (1 to 5).map{ k => i * j / k } } } scala.collection.immutable.IndexedSeq[Int] = Vector(2, 1, 0, 0, 0, 6, 3, 2, 1, 1, 10, 5, 3, 2, 2, 4, 2, 1, 1, 0, 12, 6, 4, 3, 2, 20, 10, 6, 5, 4)
A Monadic Trait ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Simplest Monad – Identity case class Identity[A](value:A) { def map[B](f:(A) => B) = Identity(f(value)) def flatMap[B](f:(A) => Identity[B]) = f(value) }
AST Evaluator ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
AST Evaluator – Identity object IdentityEvaluator extends  EvaluatorTrait[Term, Identity[Int]]  { def eval(term: Term) = term match { case Constant(x) => Identity(x) case Divide(a,b) => for (bp <- eval(b); ap <- eval(a)) yield (ap/bp) } println(eval(Divide(Divide(Constant(1972),Constant(2)), Constant(23)))) Identity(42) println(eval(Divide(Constant(1),Constant(0)))) Exception in thread &quot;main&quot; java.lang.ArithmeticException: / by zero
Useful Monad - Option ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Usefulness of Option val areaCodes = Map( &quot;Fenton&quot; -> 636, &quot;Florissant&quot; -> 314, &quot;Columbia&quot; -> 573 ) val homeTowns = Map( &quot;Moe&quot; -> &quot;Columbia&quot;, &quot;Larry&quot; -> &quot;Fenton&quot;, &quot;Curly&quot; -> &quot;Florissant&quot;,  &quot;Schemp&quot; -> &quot;St. Charles” ) def personAreaCode(person:String) =  for (homeTown <- homeTowns.get(person);   areaCode <- areaCodes.get(homeTown)) yield (areaCode)
Usefulness of Option println(personAreaCode(&quot;Moe&quot;)) Some(573) println(personAreaCode(&quot;Schemp&quot;)) None println(personAreaCode(&quot;Joe&quot;)) None println( for (areaCode <- areaCodes if areaCode._2 == 314; stoogeHome <- homeTowns if stoogeHome._2 == areaCode._1) yield stoogeHome._1 ) List(Curly) Look Mom, No null checks !!!
AST Evaluator - Option object OptionDivide  extends ((Option[Int], Option[Int]) => Option[Int]) { def apply(a:Option[Int], b:Option[Int]) = for (bp <- b; ap <- if (bp != 0) a else None) yield (ap/bp) } object OptionEvaluator extends EvaluatorTrait[Term, Option[Int]] { def eval(term: Term) = term match { case Constant(x) => Some(x) case Divide(a,b) => OptionDivide(eval(a), eval(b)) } }
AST Evaluator - Option println(eval(Divide(Divide(Constant(1972),Constant(2)), Constant(23)))) Some(42) println(eval(Divide(Constant(1),Constant(0)))) None
“ Wonkier” Monad – State object State { def unit[S,A](a:A) = new State((s:S) => (s, a)) } case class State[S, A](val s:S => (S, A)) { def map[B](f: A => B): State[S,B] =  flatMap((a:A) => State.unit(f(a))) def flatMap[B](f: A => State[S,B]): State[S,B] = State((x:S) => { val (a,y) = s(x) f(y).s(a) }) }
State Monad val add = (x:Int, y:Int) =>  State[List[String], Int]((s:List[String]) => { ((x + &quot; + &quot; + y + &quot; = &quot; + (x + y)) :: s, (x + y))  }) val sub = (x:Int, y:Int) =>  State[List[String], Int]((s:List[String]) => {    ((x + &quot; - &quot; + y + &quot; = &quot; + (x - y)) :: s, (x - y))  })  val f = for (x1 <- add(2 , 2); x2 <- sub(x1, 5); x3 <- add(x2, 2))  yield (x3) val result = f.s(Nil)  println(&quot;log = &quot; + result._1.reverse) log = List(2 + 2 = 4, 4 - 5 = -1, -1 + 2 = 1) println(&quot;result = &quot; + result._2) result = 1
State Monad – No Sugar val f = add(2,2).flatMap{ x1 =>  sub(x1, 5).flatMap { x2 =>  add(x2,2) }   }.map(identity) val result = f.s(Nil)  println(&quot;log = &quot; + result._1.reverse) log = List(2 + 2 = 4, 4 - 5 = -1, -1 + 2 = 1) println(&quot;result = &quot; + result._2) result = 1
AST Evaluator - State object StateEvaluator  extends EvaluatorTrait[Term, State[Int, Option[Int]]]  {  def eval(term: Term) = term match {  case Constant(x) => State((s:Int) => (s + x, Some(x)))  case Divide(a,b) => for ( evala <- eval(a); evalb <- eval(b)) yield OptionDivide(evala, evalb)  } println(eval(Divide(Divide(Constant(1972),Constant(2)), Constant(23))).s(0)) (1997,Some(42)) println(eval(Divide(Constant(20),Constant(0))).s(0)) (20,None)
Summary ,[object Object],[object Object],[object Object],[object Object],[object Object]
Discussion  Can monads ever be “mainstream” ?
Links James Iry – “Monads are Elephants” http://james-iry.blogspot.com/2007/09/monads-are-elephants-part-1.html http://james-iry.blogspot.com/2007/10/monads-are-elephants-part-2.html http://james-iry.blogspot.com/2007/10/monads-are-elephants-part-3.html Philip Wadler’s Monad Papers http://homepages.inf.ed.ac.uk/wadler/topics/monads.html Brian Beckman Monad Videos  http://channel9.msdn.com/shows/Going+Deep/Brian-Beckman-Dont-fear-the-Monads/ http://channel9.msdn.com/shows/Going+Deep/Brian-Beckman-The-Zen-of-Expressing-State-The-State-Monad/

Contenu connexe

Tendances

Matlab 1
Matlab 1Matlab 1
Matlab 1
asguna
 

Tendances (20)

Cs101 endsem 2014
Cs101 endsem 2014Cs101 endsem 2014
Cs101 endsem 2014
 
Arrays
ArraysArrays
Arrays
 
Martin Fowler's Refactoring Techniques Quick Reference
Martin Fowler's Refactoring Techniques Quick ReferenceMartin Fowler's Refactoring Techniques Quick Reference
Martin Fowler's Refactoring Techniques Quick Reference
 
Chapter2
Chapter2Chapter2
Chapter2
 
User Account Access Graphs
User Account Access GraphsUser Account Access Graphs
User Account Access Graphs
 
Array
ArrayArray
Array
 
Computer graphics
Computer graphics   Computer graphics
Computer graphics
 
Top school in delhi ncr
Top school in delhi ncrTop school in delhi ncr
Top school in delhi ncr
 
Sets, maps and hash tables (Java Collections)
Sets, maps and hash tables (Java Collections)Sets, maps and hash tables (Java Collections)
Sets, maps and hash tables (Java Collections)
 
Presentation
PresentationPresentation
Presentation
 
Data Visualization 2020_21
Data Visualization 2020_21Data Visualization 2020_21
Data Visualization 2020_21
 
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
 
Practical Class 12th (c++programs+sql queries and output)
Practical Class 12th (c++programs+sql queries and output) Practical Class 12th (c++programs+sql queries and output)
Practical Class 12th (c++programs+sql queries and output)
 
Arrays
ArraysArrays
Arrays
 
Matlab 1
Matlab 1Matlab 1
Matlab 1
 
Array
ArrayArray
Array
 
JS Fest 2019. Mauricio Palma. You can’t read this sentence - A11y automation
JS Fest 2019. Mauricio Palma. You can’t read this sentence - A11y automationJS Fest 2019. Mauricio Palma. You can’t read this sentence - A11y automation
JS Fest 2019. Mauricio Palma. You can’t read this sentence - A11y automation
 
DataFrame in Python Pandas
DataFrame in Python PandasDataFrame in Python Pandas
DataFrame in Python Pandas
 
Week7
Week7Week7
Week7
 
MATLAB ARRAYS
MATLAB ARRAYSMATLAB ARRAYS
MATLAB ARRAYS
 

En vedette

Zen Coding
Zen CodingZen Coding
Zen Coding
404fest
 
Relacion de plazas docentes para contrato 2013 chepen
Relacion de plazas docentes para contrato 2013  chepenRelacion de plazas docentes para contrato 2013  chepen
Relacion de plazas docentes para contrato 2013 chepen
claro
 
Illustrator Creation
Illustrator CreationIllustrator Creation
Illustrator Creation
alexinsomny
 

En vedette (20)

Practically Functional
Practically FunctionalPractically Functional
Practically Functional
 
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
 
Scala lens: An introduction
Scala lens: An introductionScala lens: An introduction
Scala lens: An introduction
 
Scalaz
ScalazScalaz
Scalaz
 
Open Space Technology progetto Sbilanciati e dì la tua!
Open Space Technology progetto Sbilanciati e dì la tua!Open Space Technology progetto Sbilanciati e dì la tua!
Open Space Technology progetto Sbilanciati e dì la tua!
 
10 Ways to Find Common Ground with Your Social Media Audience
10 Ways to Find Common Ground with Your Social Media Audience10 Ways to Find Common Ground with Your Social Media Audience
10 Ways to Find Common Ground with Your Social Media Audience
 
004 climate change scenarios for lac and rice, andy jarvis
004  climate change scenarios for lac and rice, andy jarvis004  climate change scenarios for lac and rice, andy jarvis
004 climate change scenarios for lac and rice, andy jarvis
 
Understanding How We Learn by Steve Dunn
Understanding How We Learn by Steve DunnUnderstanding How We Learn by Steve Dunn
Understanding How We Learn by Steve Dunn
 
Eggs.
Eggs.Eggs.
Eggs.
 
School Of Nursing
School Of NursingSchool Of Nursing
School Of Nursing
 
ASL BT Registro tumori 2014
ASL BT Registro tumori 2014ASL BT Registro tumori 2014
ASL BT Registro tumori 2014
 
Ripcord Public Relations: Parachute Optional
Ripcord Public Relations: Parachute OptionalRipcord Public Relations: Parachute Optional
Ripcord Public Relations: Parachute Optional
 
Incredable india...
Incredable india...Incredable india...
Incredable india...
 
Tif original 2011 final council presentation
Tif original 2011 final council presentationTif original 2011 final council presentation
Tif original 2011 final council presentation
 
Zen Coding
Zen CodingZen Coding
Zen Coding
 
Downtown Ferndale Business Guide 2011
Downtown Ferndale Business Guide 2011Downtown Ferndale Business Guide 2011
Downtown Ferndale Business Guide 2011
 
Toman Hall Of Fame
Toman Hall Of FameToman Hall Of Fame
Toman Hall Of Fame
 
Relacion de plazas docentes para contrato 2013 chepen
Relacion de plazas docentes para contrato 2013  chepenRelacion de plazas docentes para contrato 2013  chepen
Relacion de plazas docentes para contrato 2013 chepen
 
Illustrator Creation
Illustrator CreationIllustrator Creation
Illustrator Creation
 
Голос Галактики
Голос ГалактикиГолос Галактики
Голос Галактики
 

Similaire à Grokking Monads in Scala

Introduction to MatLab programming
Introduction to MatLab programmingIntroduction to MatLab programming
Introduction to MatLab programming
Damian T. Gordon
 
Scala - where objects and functions meet
Scala - where objects and functions meetScala - where objects and functions meet
Scala - where objects and functions meet
Mario Fusco
 

Similaire à Grokking Monads in Scala (20)

Monadologie
MonadologieMonadologie
Monadologie
 
Introduction to MatLab programming
Introduction to MatLab programmingIntroduction to MatLab programming
Introduction to MatLab programming
 
JBUG 11 - Scala For Java Programmers
JBUG 11 - Scala For Java ProgrammersJBUG 11 - Scala For Java Programmers
JBUG 11 - Scala For Java Programmers
 
Scala Functional Patterns
Scala Functional PatternsScala Functional Patterns
Scala Functional Patterns
 
Fp in scala part 2
Fp in scala part 2Fp in scala part 2
Fp in scala part 2
 
Scala 2 + 2 > 4
Scala 2 + 2 > 4Scala 2 + 2 > 4
Scala 2 + 2 > 4
 
User Defined Aggregation in Apache Spark: A Love Story
User Defined Aggregation in Apache Spark: A Love StoryUser Defined Aggregation in Apache Spark: A Love Story
User Defined Aggregation in Apache Spark: A Love Story
 
User Defined Aggregation in Apache Spark: A Love Story
User Defined Aggregation in Apache Spark: A Love StoryUser Defined Aggregation in Apache Spark: A Love Story
User Defined Aggregation in Apache Spark: A Love Story
 
SDC - Einführung in Scala
SDC - Einführung in ScalaSDC - Einführung in Scala
SDC - Einführung in Scala
 
Rainer Grimm, “Functional Programming in C++11”
Rainer Grimm, “Functional Programming in C++11”Rainer Grimm, “Functional Programming in C++11”
Rainer Grimm, “Functional Programming in C++11”
 
Go: It's Not Just For Google
Go: It's Not Just For GoogleGo: It's Not Just For Google
Go: It's Not Just For Google
 
The Essence of the Iterator Pattern
The Essence of the Iterator PatternThe Essence of the Iterator Pattern
The Essence of the Iterator Pattern
 
A Dimension Abstraction Approach to Vectorization in Matlab
A Dimension Abstraction Approach to Vectorization in MatlabA Dimension Abstraction Approach to Vectorization in Matlab
A Dimension Abstraction Approach to Vectorization in Matlab
 
Cgo2007 P3 3 Birkbeck
Cgo2007 P3 3 BirkbeckCgo2007 P3 3 Birkbeck
Cgo2007 P3 3 Birkbeck
 
The Essence of the Iterator Pattern (pdf)
The Essence of the Iterator Pattern (pdf)The Essence of the Iterator Pattern (pdf)
The Essence of the Iterator Pattern (pdf)
 
Will it Blend? - ScalaSyd February 2015
Will it Blend? - ScalaSyd February 2015Will it Blend? - ScalaSyd February 2015
Will it Blend? - ScalaSyd February 2015
 
Matlab1
Matlab1Matlab1
Matlab1
 
Scala - where objects and functions meet
Scala - where objects and functions meetScala - where objects and functions meet
Scala - where objects and functions meet
 
Rewriting Java In Scala
Rewriting Java In ScalaRewriting Java In Scala
Rewriting Java In Scala
 
Monads from Definition
Monads from DefinitionMonads from Definition
Monads from Definition
 

Dernier

Dernier (20)

Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdf
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 

Grokking Monads in Scala

  • 1. Grokking Monads in Scala St. Louis Lambda Lounge August 5, 2010 Tim Dalton Senior Software Engineer Object Computing Inc.
  • 2. Monads Are… Just a monoid in the category of endofunctors. Like “duh”!
  • 3.
  • 4.
  • 5.
  • 6. Scala &quot;For comprehensions&quot; for (i <- 1 to 5) yield i scala.collection.immutable.IndexedSeq[Int] = Vector(1, 2, 3, 4, 5) for (i <- 1 to 5 if i % 2 == 0) yield i scala.collection.immutable.IndexedSeq[Int] = Vector(2, 4) for (i <-1 to 5 if i % 2 == 0) { print (i + &quot; &quot; ) } 2 4 for (i <-1 to 5 if i % 2 == 0; j <- 1 to 5 if j % 2 != 0) yield ( i * j ) scala.collection.immutable.IndexedSeq[Int] = Vector(2, 6, 10, 4, 12, 20) for (i <-1 to 5 if i % 2 == 0; j <- 1 to 5 if j % 2 != 0; k <- 1 to 5) yield ( i * j / k ) scala.collection.immutable.IndexedSeq[Int] = Vector(2, 1, 0, 0, 0, 6, 3, 2, 1, 1, 10, 5, 3, 2, 2, 4, 2, 1, 1, 0, 12, 6, 4, 3, 2, 20, 10, 6, 5, 4)
  • 7. De-sugarized For comprehensions (1 to 5).map(identity) scala.collection.immutable.IndexedSeq[Int] = Vector(1, 2, 3, 4, 5) (1 to 5).filter{_ % 2 == 0}.map(identity) scala.collection.immutable.IndexedSeq[Int] = Vector(2, 4) (1 to 5).filter{_ % 2 == 0}.foreach { i => print (i + &quot; &quot; ) } 2 4 (1 to 5).filter{_ % 2 == 0}.flatMap { i => (1 to 5).filter{_ % 2 != 0}.map{ j => i * j } } scala.collection.immutable.IndexedSeq[Int] = Vector(2, 6, 10, 4, 12, 20) (1 to 5).filter{_ % 2 == 0}.flatMap { i => (1 to 5).filter{_ % 2 != 0}.flatMap{ j => (1 to 5).map{ k => i * j / k } } } scala.collection.immutable.IndexedSeq[Int] = Vector(2, 1, 0, 0, 0, 6, 3, 2, 1, 1, 10, 5, 3, 2, 2, 4, 2, 1, 1, 0, 12, 6, 4, 3, 2, 20, 10, 6, 5, 4)
  • 8.
  • 9. Simplest Monad – Identity case class Identity[A](value:A) { def map[B](f:(A) => B) = Identity(f(value)) def flatMap[B](f:(A) => Identity[B]) = f(value) }
  • 10.
  • 11. AST Evaluator – Identity object IdentityEvaluator extends EvaluatorTrait[Term, Identity[Int]] { def eval(term: Term) = term match { case Constant(x) => Identity(x) case Divide(a,b) => for (bp <- eval(b); ap <- eval(a)) yield (ap/bp) } println(eval(Divide(Divide(Constant(1972),Constant(2)), Constant(23)))) Identity(42) println(eval(Divide(Constant(1),Constant(0)))) Exception in thread &quot;main&quot; java.lang.ArithmeticException: / by zero
  • 12.
  • 13. Usefulness of Option val areaCodes = Map( &quot;Fenton&quot; -> 636, &quot;Florissant&quot; -> 314, &quot;Columbia&quot; -> 573 ) val homeTowns = Map( &quot;Moe&quot; -> &quot;Columbia&quot;, &quot;Larry&quot; -> &quot;Fenton&quot;, &quot;Curly&quot; -> &quot;Florissant&quot;, &quot;Schemp&quot; -> &quot;St. Charles” ) def personAreaCode(person:String) = for (homeTown <- homeTowns.get(person); areaCode <- areaCodes.get(homeTown)) yield (areaCode)
  • 14. Usefulness of Option println(personAreaCode(&quot;Moe&quot;)) Some(573) println(personAreaCode(&quot;Schemp&quot;)) None println(personAreaCode(&quot;Joe&quot;)) None println( for (areaCode <- areaCodes if areaCode._2 == 314; stoogeHome <- homeTowns if stoogeHome._2 == areaCode._1) yield stoogeHome._1 ) List(Curly) Look Mom, No null checks !!!
  • 15. AST Evaluator - Option object OptionDivide extends ((Option[Int], Option[Int]) => Option[Int]) { def apply(a:Option[Int], b:Option[Int]) = for (bp <- b; ap <- if (bp != 0) a else None) yield (ap/bp) } object OptionEvaluator extends EvaluatorTrait[Term, Option[Int]] { def eval(term: Term) = term match { case Constant(x) => Some(x) case Divide(a,b) => OptionDivide(eval(a), eval(b)) } }
  • 16. AST Evaluator - Option println(eval(Divide(Divide(Constant(1972),Constant(2)), Constant(23)))) Some(42) println(eval(Divide(Constant(1),Constant(0)))) None
  • 17. “ Wonkier” Monad – State object State { def unit[S,A](a:A) = new State((s:S) => (s, a)) } case class State[S, A](val s:S => (S, A)) { def map[B](f: A => B): State[S,B] = flatMap((a:A) => State.unit(f(a))) def flatMap[B](f: A => State[S,B]): State[S,B] = State((x:S) => { val (a,y) = s(x) f(y).s(a) }) }
  • 18. State Monad val add = (x:Int, y:Int) => State[List[String], Int]((s:List[String]) => { ((x + &quot; + &quot; + y + &quot; = &quot; + (x + y)) :: s, (x + y)) }) val sub = (x:Int, y:Int) => State[List[String], Int]((s:List[String]) => { ((x + &quot; - &quot; + y + &quot; = &quot; + (x - y)) :: s, (x - y)) }) val f = for (x1 <- add(2 , 2); x2 <- sub(x1, 5); x3 <- add(x2, 2)) yield (x3) val result = f.s(Nil) println(&quot;log = &quot; + result._1.reverse) log = List(2 + 2 = 4, 4 - 5 = -1, -1 + 2 = 1) println(&quot;result = &quot; + result._2) result = 1
  • 19. State Monad – No Sugar val f = add(2,2).flatMap{ x1 => sub(x1, 5).flatMap { x2 => add(x2,2) } }.map(identity) val result = f.s(Nil) println(&quot;log = &quot; + result._1.reverse) log = List(2 + 2 = 4, 4 - 5 = -1, -1 + 2 = 1) println(&quot;result = &quot; + result._2) result = 1
  • 20. AST Evaluator - State object StateEvaluator extends EvaluatorTrait[Term, State[Int, Option[Int]]] { def eval(term: Term) = term match { case Constant(x) => State((s:Int) => (s + x, Some(x))) case Divide(a,b) => for ( evala <- eval(a); evalb <- eval(b)) yield OptionDivide(evala, evalb) } println(eval(Divide(Divide(Constant(1972),Constant(2)), Constant(23))).s(0)) (1997,Some(42)) println(eval(Divide(Constant(20),Constant(0))).s(0)) (20,None)
  • 21.
  • 22. Discussion Can monads ever be “mainstream” ?
  • 23. Links James Iry – “Monads are Elephants” http://james-iry.blogspot.com/2007/09/monads-are-elephants-part-1.html http://james-iry.blogspot.com/2007/10/monads-are-elephants-part-2.html http://james-iry.blogspot.com/2007/10/monads-are-elephants-part-3.html Philip Wadler’s Monad Papers http://homepages.inf.ed.ac.uk/wadler/topics/monads.html Brian Beckman Monad Videos http://channel9.msdn.com/shows/Going+Deep/Brian-Beckman-Dont-fear-the-Monads/ http://channel9.msdn.com/shows/Going+Deep/Brian-Beckman-The-Zen-of-Expressing-State-The-State-Monad/

Notes de l'éditeur

  1. I personally find the spacesuit metaphor the most helpful
  2. Return == unit
  3. Return == unit
  4. flatMap for Scala sequences and lists implement the List Monad
  5. No unit method is implemented here. Oftentimes constructors act has units. There are some high-level functions that can operate over different types of monads that often need a unit function Identity pretty much put the “astronaut in another suit”
  6. State in this case sums the constants (kind of contrived)
  7. State in this case sums the constants (kind of contrived)
  8. State in this case sums the constants (kind of contrived)