Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Introduction to Monads in Scala (1)

11,511 views

Published on

Published in: Technology, Business
  • Be the first to comment

Introduction to Monads in Scala (1)

  1. 1. Monads Part 1functional programming with scala
  2. 2. Where r the verbs lost?
  3. 3. Thinking in Use Cases get the coffee meet with colleagues on the kitchen read emails review social media update the workspace write the code
  4. 4. Thinking in JavaCompanyHolder.getStuffFactoryBuilder(). buildCurrentState(). find(Rooms.KITCHEN, CoffeMachine.Any). get(0). run(new CoffeeJob( me.getHabitsStore().find("coffe"). mapToJobMachnie(), null));
  5. 5. Thinking in JavaNeed an update:new SVNUpdateJob(myProject).go();• execute• process• run• start• doIt
  6. 6. Thinking in JavaCheck GmailMySmartProxyHack.go();go via Hack or Job – action name isnt important
  7. 7. QHow many times u were not lucky withfact that do is the keyword?ProjectManager.do() vs manageSecurityProcessor.do() vs process
  8. 8. Guava from GBad library: it makes me feeling smellPreconditions.checkArgument(...) vscheckArgument(...)withstatic import... but this is a way for nonlazy dudes in Java
  9. 9. Patriots in JavaFirst action is create, get, find, build, ...?Use a Spring, Guice!!!
  10. 10. Other ways of thinkingC and C++Python
  11. 11. Evil?We r smart – look into Python,Ruby, Java Script or Perl – gun meat.Im smart enough to understandAbstractProxyMediator orNotificationStrategyFactory– they even dont have it!
  12. 12. Monad is …
  13. 13. Monad isUsually articles that start with words like"monad" and "functor" quickly devolve intosoup of Greek letters. Thats because both areabstract concepts in a branch of mathematicscalled category theory and explaining themcompletely is a mathematical exercise. JAMES IRY
  14. 14. Stateless paradigm
  15. 15. JEE Session Facade stack trace
  16. 16. Functions …F1(F2(F3(F4(Xinput))))
  17. 17. Jump to ScalaFew syntax details to understand examples
  18. 18. val, Listval act1 = List ("Leonardo" , "Raphael")
  19. 19. List operations, Nilval act2 = “April” :: "Donatello" :: Nilval act3 = act1 ::: act2
  20. 20. Var, no sugarvar act4:List[String] = act3act4 = "Michelangelo" :: act4
  21. 21. Function(x: Int) => x * 2
  22. 22. Function as valueval double = (x: Int) => x * 2double(10)
  23. 23. SugarList(1,2,3).foreach ( (x:Int) => println ( x ) )List(1,2,3).foreach ( x => println ( x ) )List(1,2,3).foreach ( println _ )List(1,2,3).foreach ( println )
  24. 24. Yieldval result = for (i <- 1 to 5) yield iVector(1, 2, 3, 4, 5)
  25. 25. Traittrait Manager extends Lead{ private var workSchedule:Schedule = … override def schedule = workSchedule}class College extends Worker with Manager withWellpaid with HardToFind
  26. 26. 1. Monads are Container Types Option, List, …
  27. 27. Where is my manager?Company company = getCompany();Manager manager = company.findManager();if (manager != null) { manager.getBonusFor(me);} else { System.out.println("As always...");}
  28. 28. Schrödingers Statepublic interface Option<T> { public T value(); public boolean hasValue();}Company company = getCompany();Option<Manager> manager = company.findManager();if (manager.hasValue()) { manager.getBonusFor(me);} else { System.out.println(”Arent news!");}
  29. 29. Optiontrait Manager { def getBonusFor(id: Long) :Option[Double]}trait Company { def manager:Manager}val sum = getCompany().manager. getBonusFor(myId)val bonus = sum match { case Some(bonus) => bonus case None => 0}
  30. 30. 0 on defaultval myBonus = manager.getOrElse(0)
  31. 31. 0 on defaultval myBonus = manager.getOrElse(0)
  32. 32. If in IfCompany company = getCompany(); if (company != null) { Manager manager = company.findManager(); if (manager != null) { double bonus = manager.getBonusFor(me); ... } else { System.out.println("Isnt news!"); } }
  33. 33. Or Elseval m =company.getManager.getOrElse(ManagmentFactory.newOne)m.getBonusFor(me).getOrElse(…)
  34. 34. Option is a monadfor ( c <- getCompany; m <- c.getManagerFor(me); b <- m.getBonusFor(me)) b spend
  35. 35. 2. Monads Support Higher Order Functionsval list = List(1, 2, 3)def neg (elem: Int) = -elemval mapResult = list map negList(1,2,3) map {-_}
  36. 36. Doesn’t change the kind of monad, butmay change its parameterized type...val one = Some(1)val oneString = one map {_.toString}assert (oneString == Some("1"))
  37. 37. 3. Monads are Combinableval opMan : Option[Manager] = companygetManagerdef extractBonus(m:Manager) : Option[Double]= ...val result = opMan map extractBonusOption[Option[Double]]
  38. 38. List[List[Int]]]List[List[List[Int]]]]
  39. 39. Flattendef flatten[A](outer:Option[Option[A]]) : Option[A] = outer match { case None => None case Some(inner) => inner }If the outer option is None, then result is None.Otherwise the result is the inner Option.
  40. 40. Join, Flatten etcScala does not require you to write flatten explicitly.But it does require that each monad have a methodcalled flatMap.class M[A] { private def flatten[B](x:M[M[B]]) : M[B] = ... def map[B](f: A => B) : M[B] = ... def flatMap[B](f: A => M[B]) : M[B] = flatten(map(f))}
  41. 41. Reviewval opMan : Option[Manager] = companygetManagerdef extractBonus(m:Manager) : Option[Double]= ...val result = opMan flatMap extractBonusOption[Double]
  42. 42. 4. Monads Can Be Built In Different Ways ”unit,” in Haskell its called “return”single argument “constructor” or ”actory” A become a monad of type M[A] For List: unit(x) == List(x) For Option: unit(x) == Some(x)
  43. 43. class M[A](value: A) { private def unit[B] (value : B) = new M(value) …}
  44. 44. Map based on flatMapScala does not require a separate "unit" function ormethodclass M[A](value: A) { private def unit[B] (value : B) = new M(value) def map[B](f: A => B) : M[B] = flatMap {x => unit(f(x))} def flatMap[B](f: A => M[B]) : M[B] = ...}
  45. 45. Basis 1Generic Haskell ScalaM data M a class M[A] or newtype M a or case class M[A] or instance Monad (M a) or trait M[A]Ma Ma M[A]unit v return v new M(v) or M(v)map f m fmap f m m map fbind f m m >>= f m flatMap f or f =<< mjoin join flatten do for

×