Skip to content

Instantly share code, notes, and snippets.

@joost-de-vries
Forked from headinthebox/gist:37c76829253388fd88e3
Last active August 29, 2015 14:02
Show Gist options
  • Save joost-de-vries/31ad91d7299b08503684 to your computer and use it in GitHub Desktop.
Save joost-de-vries/31ad91d7299b08503684 to your computer and use it in GitHub Desktop.
Erik Meijers foldleft implementation using foldright rewritten in Scala
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
Copy link

def foldl[B,A](a:A)(f:(A,B)=>A)(bs:Seq[B]):A=bs.foldRight((a:A)=>a)((b:B,g:A=>A)=>(a:A)=>g(f(a,b)))(a)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment