Advertisement
linasm

Scala for-comprehensions presentation

Jul 20th, 2017
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 1.42 KB | None | 0 0
  1. sealed abstract class Perhaps[+A] {
  2.   def foreach(f: A => Unit): Unit
  3.   def map[B](f: A => B): Perhaps[B]
  4.   def flatMap[B](f: A => Perhaps[B]): Perhaps[B]
  5.   def withFilter(f: A => Boolean): Perhaps[A]
  6. }
  7.  
  8. case class YesIHas[A](value: A) extends Perhaps[A] {
  9.   override def foreach(f: (A) => Unit): Unit = f(value)
  10.   override def map[B](f: (A) => B): Perhaps[B] = YesIHas(f(value))
  11.   override def flatMap[B](f: (A) => Perhaps[B]): Perhaps[B] = f(value)
  12.   override def withFilter(f: (A) => Boolean): Perhaps[A] = if (f(value)) this else Nope
  13. }
  14.  
  15. case object Nope extends Perhaps[Nothing] {
  16.   override def foreach(f: (Nothing) => Unit): Unit = ()
  17.   override def map[B](f: (Nothing) => B): Perhaps[B] = this
  18.   override def flatMap[B](f: (Nothing) => Perhaps[B]): Perhaps[B] = this
  19.   override def withFilter(f: (Nothing) => Boolean): Perhaps[Nothing] = this
  20. }
  21.  
  22. val x1 = YesIHas(3)
  23. val x2 = YesIHas(5)
  24.  
  25. // foreach:
  26. x1.foreach(a => println(a))
  27.  
  28. for {
  29.   a <- x1
  30. } println(a)
  31.  
  32. // map:
  33. x1.map(a => a * 5)
  34.  
  35. for {
  36.   a <- x1
  37. } yield a * 5
  38.  
  39. // flatMap/map:
  40. x1.flatMap(a => x2.map(b => a * b))
  41.  
  42. for {
  43.   a <- x1
  44.   b <- x2
  45.   if b > 3
  46. } yield a * b
  47.  
  48. // withFilter:
  49. x1.withFilter(a => a > 1).flatMap(a => x2.map(b => a * b))
  50.  
  51. for {
  52.   a <- x1
  53.   //if a > 1
  54.   b <- x2
  55. } yield a * b
  56.  
  57. // assignment:
  58. x1.flatMap { a =>
  59.   x2.map { b =>
  60.     val c = a * b
  61.     c
  62.   }
  63. }
  64.  
  65. for {
  66.   a <- x1
  67.   b <- x2
  68.   c = a * b
  69. } yield c
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement