Skip to content

Instantly share code, notes, and snippets.

@debasishg
Created January 2, 2011 18:56
Show Gist options
  • Save debasishg/762736 to your computer and use it in GitHub Desktop.
Save debasishg/762736 to your computer and use it in GitHub Desktop.
wordcount example in scalaz using State monad
import scalaz._
import Scalaz._
def charLineCount[T[_]:Traverse](t: T[Char]) =
t.traverse[({type λ[x] = State[(Int, Int),x]})#λ, (Int, Int)](a =>
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)
@channingwalton
Copy link

Thanks for this, I am trying to grok the state monad at the moment and this helps.

@debasishg
Copy link
Author

There's a nice example in scalaz examples distribution too ..

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