-
-
Save joost-de-vries/31ad91d7299b08503684 to your computer and use it in GitHub Desktop.
Erik Meijers foldleft implementation using foldright rewritten in Scala
This file contains hidden or 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
object foldfun { | |
def foldr[A, B](f: A => B => B)(b: B)(s: Seq[A]): B = s match { | |
case Nil => b | |
case a :: as => | |
f(a)(foldr(f)(b)(as)) | |
} //> foldr: [A, B](f: A => (B => B))(b: B)(s: Seq[A])B | |
foldr { a: String => b: Int => a.toInt * b.toInt }(7)(Seq("1", "2", "3")) | |
//> res0: Int = 42 | |
def foldl[A, B](f: (A, B) => A)(a: A)(s: Seq[B]): A = s match { | |
case Nil => a | |
case b :: bs => | |
foldl(f)(f(a, b))(bs) | |
} //> foldl: [A, B](f: (A, B) => A)(a: A)(s: Seq[B])A | |
foldl((a: Int, b: String) => a * b.toInt)(7)(Seq("1", "2", "3")) | |
//> res1: Int = 42 | |
def foldl2[A, B](f: A => B => A)(a: A)(s: Seq[B]): A = { | |
def k[X](b: B)(g: A => X): A => X = { a2: A => | |
g(f(a2)(b)) | |
} | |
//foldr k {a3:A => a3} s a | |
??? | |
} //> foldl2: [A, B](f: A => (B => A))(a: A)(s: Seq[B])A | |
} |
headinthebox
commented
Jun 21, 2014
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment