Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- sealed abstract class Perhaps[+A] {
- def foreach(f: A => Unit): Unit
- def map[B](f: A => B): Perhaps[B]
- def flatMap[B](f: A => Perhaps[B]): Perhaps[B]
- def withFilter(f: A => Boolean): Perhaps[A]
- }
- case class YesIHas[A](value: A) extends Perhaps[A] {
- override def foreach(f: (A) => Unit): Unit = f(value)
- override def map[B](f: (A) => B): Perhaps[B] = YesIHas(f(value))
- override def flatMap[B](f: (A) => Perhaps[B]): Perhaps[B] = f(value)
- override def withFilter(f: (A) => Boolean): Perhaps[A] = if (f(value)) this else Nope
- }
- case object Nope extends Perhaps[Nothing] {
- override def foreach(f: (Nothing) => Unit): Unit = ()
- override def map[B](f: (Nothing) => B): Perhaps[B] = this
- override def flatMap[B](f: (Nothing) => Perhaps[B]): Perhaps[B] = this
- override def withFilter(f: (Nothing) => Boolean): Perhaps[Nothing] = this
- }
- val x1 = YesIHas(3)
- val x2 = YesIHas(5)
- // foreach:
- x1.foreach(a => println(a))
- for {
- a <- x1
- } println(a)
- // map:
- x1.map(a => a * 5)
- for {
- a <- x1
- } yield a * 5
- // flatMap/map:
- x1.flatMap(a => x2.map(b => a * b))
- for {
- a <- x1
- b <- x2
- if b > 3
- } yield a * b
- // withFilter:
- x1.withFilter(a => a > 1).flatMap(a => x2.map(b => a * b))
- for {
- a <- x1
- //if a > 1
- b <- x2
- } yield a * b
- // assignment:
- x1.flatMap { a =>
- x2.map { b =>
- val c = a * b
- c
- }
- }
- for {
- a <- x1
- b <- x2
- c = a * b
- } yield c
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement