Skip to content

Instantly share code, notes, and snippets.

@debasishg
Created January 3, 2011 18:37
Show Gist options
  • Save debasishg/763759 to your computer and use it in GitHub Desktop.
Save debasishg/763759 to your computer and use it in GitHub Desktop.
// disperse implementation corresponding to the same function in section 4.2 of the paper
// Essence of the Iterator Pattern
def disperse[T[_]:Traverse, A, S, B](t: T[A], s: A => State[S, B]) =
t.traverse[({type λ[x] = State[S,x]})#λ, B](s)
// implementing a labeling function, also from section 4.2
// labeling every element with its position in order of traversal
def label_[T[_]:Traverse, A](t: T[A]) = disperse(t, ((a: A) => state((i: Int) => (i+1, i)))) ! 0
println(label_(List(102, 207, 876, 14)) // List(0,1,2,3)
// scalaz example of wordcount
// look ma .. no type lambas
def charLineCount_[T[_]:Traverse](t: T[Char]) =
disperse(t, ((a: Char) => state((counts: (Int, Int)) =>
((counts._1 + 1, counts._2 + (if (a == '\n') 1 else 0)), (counts._1, counts._2))))) ! (1,1)
println(charLineCount_("the cat in the hat\n sat on the mat\n".toList).last) // (35,2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment