Skip to content

Instantly share code, notes, and snippets.

@debasishg
Created January 2, 2011 05:47
Show Gist options
  • Save debasishg/762328 to your computer and use it in GitHub Desktop.
Save debasishg/762328 to your computer and use it in GitHub Desktop.
loop and label implementation of the Essence of the Iterator Pattern
import scalaz._
import Scalaz._
val l = List(10, 20, 30, 40)
// loop from The Essence of the Iterator Pattern
// accumulates elements effectfully, but modifies elements purely and independently of accumulation
def loop[T[_]:Traverse, A, B](f: A => B, t: T[A]) =
t.traverse[({type λ[x] = State[Int,x]})#λ, (B, Int)](a =>
state((i: Int) => (i+1, (f(a), i)))) ! 0
loop((a: Int) => 2 * a, l) should equal(List[(Int, Int)] = List((20,0), (40,1), (60,2), (80,3)))
// label from The Essence of the Iterator Pattern
// modifies elements purely but dependent on the state evolving this state independently of the elements
def label[T[_]:Traverse, A, B](t: T[A]) =
t.traverse[({type λ[x] = State[Int,x]})#λ, Int](a =>
state((i: Int) => (i+1, i))) ! 0
label(l) should equal(List(0,1,2,3))
Now need to work on the higher level abstractions *collect* & *disperse* ..
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment