Created
July 11, 2015 18:42
-
-
Save seraphr/78ad38b1c60a8fb78d72 to your computer and use it in GitHub Desktop.
foldRightのfoldLeftを用いた実装。 ついでにstackless
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
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