Skip to content

Instantly share code, notes, and snippets.

@itang
Created June 18, 2021 02:08
Show Gist options
  • Save itang/0cf959051bcbd67d2cb923d7bf4d6374 to your computer and use it in GitHub Desktop.
Save itang/0cf959051bcbd67d2cb923d7bf4d6374 to your computer and use it in GitHub Desktop.
import scala.jdk.CollectionConverters._
import scala.util.chaining._
case class Myforable[A](v: List[A]):
def foreach[T](f: A => T): Unit = v.foreach(f)
def map[T](f: A => T): Myforable[T] = Myforable(v.map(f))
def flatMap[T](f: A => Myforable[T]): Myforable[T] =
val list: List[T] = v.map(f).map(_.v).flatten
Myforable(list)
def withFilter(f: A => Boolean): Myforable[A] = Myforable(v.filter(f))
object Main:
def main(args: Array[String]): Unit = time {
val m = Myforable(List("a", "b"))
for it <- m do //need foreach method
println(it)
val m2 = for (it <- m) yield it + "_" // need map method
println(m2)
val m3 = for {
it <- m // need flatMap method
it2 <- m
} yield it + "_" + it2
println(m3)
val m33 = m.flatMap(it => m.map(it2 => it + "_" + it2))
println(m33)
val m4 = for {
it <- m // need withFilter method
if it.chars().findFirst().orElse(0) > 'a'.toInt
it2 <- m
} yield it + "_" + it2
println(m4)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment