Skip to content

Instantly share code, notes, and snippets.

@Biacco42
Created October 13, 2017 17:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Biacco42/43bff5c0477366537fc5de8c6f848d2c to your computer and use it in GitHub Desktop.
Save Biacco42/43bff5c0477366537fc5de8c6f848d2c to your computer and use it in GitHub Desktop.
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