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

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 ReferenceSeung-Bum Lee
 
Top school in delhi ncr
Top school in delhi ncrTop school in delhi ncr
Top school in delhi ncrEdhole.com
 
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)Fulvio Corno
 
Data Visualization 2020_21
Data Visualization 2020_21Data Visualization 2020_21
Data Visualization 2020_21Sangita Panchal
 
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
 
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) Aman Deep
 
Matlab 1
Matlab 1Matlab 1
Matlab 1asguna
 
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 automationJSFestUA
 
DataFrame in Python Pandas
DataFrame in Python PandasDataFrame in Python Pandas
DataFrame in Python PandasSangita Panchal
 

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

Practically Functional
Practically FunctionalPractically Functional
Practically Functionaldjspiewak
 
Optics with monocle - Modeling the part and the whole
Optics with monocle - Modeling the part and the wholeOptics with monocle - Modeling the part and the whole
Optics with monocle - Modeling the part and the wholeIlan Godik
 
Scala lens: An introduction
Scala lens: An introductionScala lens: An introduction
Scala lens: An introductionKnoldus Inc.
 
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!Conetica
 
ASL BT Registro tumori 2014
ASL BT Registro tumori 2014ASL BT Registro tumori 2014
ASL BT Registro tumori 2014Conetica
 
Zen Coding
Zen CodingZen Coding
Zen Coding404fest
 
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 chepenclaro
 
Illustrator Creation
Illustrator CreationIllustrator Creation
Illustrator Creationalexinsomny
 

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

Monadologie
MonadologieMonadologie
Monadologieleague
 
Introduction to MatLab programming
Introduction to MatLab programmingIntroduction to MatLab programming
Introduction to MatLab programmingDamian T. Gordon
 
JBUG 11 - Scala For Java Programmers
JBUG 11 - Scala For Java ProgrammersJBUG 11 - Scala For Java Programmers
JBUG 11 - Scala For Java ProgrammersTikal Knowledge
 
Scala Functional Patterns
Scala Functional PatternsScala Functional Patterns
Scala Functional Patternsleague
 
Fp in scala part 2
Fp in scala part 2Fp in scala part 2
Fp in scala part 2Hang Zhao
 
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 StoryDatabricks
 
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 StoryDatabricks
 
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”Platonov Sergey
 
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 GoogleEleanor McHugh
 
The Essence of the Iterator Pattern
The Essence of the Iterator PatternThe Essence of the Iterator Pattern
The Essence of the Iterator PatternEric Torreborre
 
Cgo2007 P3 3 Birkbeck
Cgo2007 P3 3 BirkbeckCgo2007 P3 3 Birkbeck
Cgo2007 P3 3 BirkbeckaiQUANT
 
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 MatlabaiQUANT
 
The Essence of the Iterator Pattern (pdf)
The Essence of the Iterator Pattern (pdf)The Essence of the Iterator Pattern (pdf)
The Essence of the Iterator Pattern (pdf)Eric Torreborre
 
Will it Blend? - ScalaSyd February 2015
Will it Blend? - ScalaSyd February 2015Will it Blend? - ScalaSyd February 2015
Will it Blend? - ScalaSyd February 2015Filippo Vitale
 
Scala - where objects and functions meet
Scala - where objects and functions meetScala - where objects and functions meet
Scala - where objects and functions meetMario Fusco
 
Rewriting Java In Scala
Rewriting Java In ScalaRewriting Java In Scala
Rewriting Java In ScalaSkills Matter
 
Monads from Definition
Monads from DefinitionMonads from Definition
Monads from DefinitionDierk König
 

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
 
Cgo2007 P3 3 Birkbeck
Cgo2007 P3 3 BirkbeckCgo2007 P3 3 Birkbeck
Cgo2007 P3 3 Birkbeck
 
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
 
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

Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityIES VE
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demoHarshalMandlekar2
 
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...AliaaTarek5
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Mark Goldstein
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationKnoldus Inc.
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch TuesdayIvanti
 
Manual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditManual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditSkynet Technologies
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Scott Andery
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesKari Kakkonen
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rick Flair
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...Wes McKinney
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 

Dernier (20)

Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a reality
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demo
 
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog Presentation
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch Tuesday
 
Manual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditManual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance Audit
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examples
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 

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)