Skip to content

Instantly share code, notes, and snippets.

@diesalbla
Last active August 1, 2020 21:56
Show Gist options
  • Save diesalbla/d79c2beffa049f2cf008596813f61196 to your computer and use it in GitHub Desktop.
Save diesalbla/d79c2beffa049f2cf008596813f61196 to your computer and use it in GitHub Desktop.
Lazy Fold Right
type Lazy[A] = () => A
def foldRight[A, B](xs: List[A], z: B)(f: (A, Lazy[B]) => B): B =
xs match {
case Nil => z
case h :: t => f(h, () => foldRight(t, z)(f))
}
def find[A](xs: List[A])(p: A => Boolean): Option[A] = {
val init = Option.empty[A]
def ite(a: A, rest: Lazy[Option[A]]): Option[A] =
if (p(a)) Some(a) else rest()
foldRight[A, Option[A]](xs, init)(ite(_, _))
}
// For a quick example
val ss: List[Int] = (1 to 20).toList
def is13(i: Int): Boolean = {
val b = i == 13
if (b) println(s"$i IS YAI 13") else println(s"$i IS NOT 13")
b
}
find(ss)(is13)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment