Created
October 13, 2017 17:02
-
-
Save Biacco42/43bff5c0477366537fc5de8c6f848d2c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
object Main extends App{ | |
val forPo = new Forable("Po") | |
val po = for { | |
u <- forPo | |
} yield u | |
println(po) | |
// Kaboom! Cannot compile - lack of flatMap | |
// val popo = for { | |
// u <- forPo | |
// v <- forPo | |
// } yield u + v | |
val multiForPo = new MultiForable("Po") | |
val multiForPoPo = new MultiForable("PoPo") | |
val popopo = for { | |
po <- multiForPo | |
popo <- multiForPoPo | |
} yield po + popo | |
println(popopo) | |
// Kaboom! Cannot compile - lack of foreach | |
// for { | |
// po <- multiForPo | |
// popo <- multiForPoPo | |
// } println(po + popo) | |
val sideEffectPo = new SideEffectForable("Po") | |
val sideEffectPoPo = new SideEffectForable("PoPo") | |
for { | |
po <- sideEffectPo | |
popo <- sideEffectPoPo | |
} println(po + popo) | |
// Kaboom! Cannot compile - lack of filter | |
// val popo = for { | |
// popo <- multiForPoPo if multiForPoPo.x == "Po" | |
// } yield popo | |
val filterPoPo = new FilterForable("PoPo") | |
val popo = for { | |
popo <- filterPoPo if filterPoPo.x == "PoPo" | |
} yield popo | |
println(popo) | |
} | |
class Forable[A](val x: A) { | |
def map[B](f: A => B): Forable[B] = new Forable(f(x)) | |
override def toString(): String = x.toString | |
} | |
class MultiForable[A](x: A) extends Forable(x) { | |
def flatMap[B](f: A => Forable[B]): Forable[B] = f(x) | |
} | |
class SideEffectForable[A](val x: A) { | |
def foreach(f: A => Unit): Unit = f(x) | |
} | |
class FilterForable[A](x: A) extends MultiForable(x) { | |
def withFilter(expr: A => Boolean): FilterForable[A] = this // easy implementation | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment