Skip to content

Instantly share code, notes, and snippets.

@seraphr
Created July 11, 2015 18:42
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 seraphr/78ad38b1c60a8fb78d72 to your computer and use it in GitHub Desktop.
Save seraphr/78ad38b1c60a8fb78d72 to your computer and use it in GitHub Desktop.
foldRightのfoldLeftを用いた実装。 ついでにstackless
def foldRightSimple[A, B](l: List[A])(z: B)(f: (A, B) => B): B = l match {
case Nil => z
case x :: xs => f(x, foldRightSimple(xs)(z)(f))
}
trait Trampoline[T]
case class Done[T](v: T) extends Trampoline[T]
case class Suspend[T](f: () => Trampoline[T]) extends Trampoline[T]
@annotation.tailrec
def runTrampoline[T](t: Trampoline[T]): T = t match {
case Done(t) => t
case Suspend(f) => runTrampoline(f())
}
def foldRightUsingFoldLeft[A, B](l: List[A])(z: B)(f: (A, B) => B): B = {
val tTrampoline = l.foldLeft((b: B) => Done(b): Trampoline[B]) { (accF, e) =>
acc => Suspend(() => accF(f(e, acc)))
}
runTrampoline(tTrampoline(z))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment