Skip to content

Instantly share code, notes, and snippets.

View andrewharmellaw's full-sized avatar

Andrew Harmel-Law andrewharmellaw

View GitHub Profile
@andrewharmellaw
andrewharmellaw / foldLeft_TakeOne.scala
Last active November 15, 2015 20:19
folding_blog_post-gist1
def foldLeft[A,B](as: List[A], b: B)(f: (B, A) => B): B
as match {
case Nil => b
case Cons(h,t) => foldLeft(t, f(b, h))(f)
}
@andrewharmellaw
andrewharmellaw / foldRight_TakeOne_ImplAndSimpleTrace.scala
Last active November 15, 2015 20:42
Implementation and simple trace of a foldRight (from Functional Programming in Scala, chapter 3)
def foldRight[A,B](as: List[A], b: B)(f: (A, B) => B): B =
as match {
case Nil => b
case Cons(x, xs) => f(x, foldRight(xs, b)(f))
}
foldRight(List(1, 2, 3)) ((x,y) => x + y)
foldRight(Cons(1, Cons(2, Cons(3, Nil))), 0) ((x,y) => x + y)
1 + foldRight(Cons(2, Cons(3, Nil)), 0) ((x,y) => x + y)
1 + (2 + foldRight(Cons(3, Nil), 0) ((x,y) => x + y))
@andrewharmellaw
andrewharmellaw / foldLeft_TakeOne_SimpleTrace.scala
Last active November 15, 2015 20:43
Trace of a simple foldLeft
foldLeft(List(1,2,3), 0) (_ + _)
foldLeft(Cons(1, Cons(2, Cons(3, Nil))), 0) (_ + _)
foldLeft(Cons(2, Cons(3, Nil)), (0 + 1)) (_ + _)
foldLeft(Cons(3, Nil), ((0 + 1) + 2)) (_ + _)
foldLeft(Nil, (((0 + 1) + 2) + 3)) (_ + _)
(((0 + 1) + 2) + 3))
@andrewharmellaw
andrewharmellaw / foldLeft_and_foldRight-The_Meaty_Bits.scala
Created November 16, 2015 20:53
The meaty bits of foldLeft and foldRight
// foldLeft's meaty bit
case Cons(h,t) => foldLeft(t, f(b, h))(f)
// foldRight meaty bit
case Cons(x, xs) => f(x, foldRight(xs, b)(f))
foldLeft(List(1,2,3), 0)(_ + _)
def foldLeft[A,B](as: List[A], b: B)(f: (B, A) => B): B = as match {
case Nil => b
case h :: t => foldLeft(t, f(b, h))(f)
}
foldLeft(2 :: 3 :: Nil, (0 + 1)) (_ + _)
foldLeft(2 :: 3 :: Nil, (0 + 1)) (_ + _)
foldLeft(List(1,2,3), 0) (_ + _)
foldLeft(1 :: 2 :: 3 :: Nil, 0) (_ + _)
foldLeft(2 :: 3 :: Nil, f(0, 1)) (_ + _)
foldLeft(2 :: 3 :: Nil, (0 + 1)) (_ + _)
foldLeft(3 :: Nil, ((0 + 1) + 2)) (_ + _)