Skip to content

Instantly share code, notes, and snippets.

@bmjames
Forked from debasishg/gist:762736
Created June 5, 2012 14:48
Show Gist options
  • Save bmjames/2875449 to your computer and use it in GitHub Desktop.
Save bmjames/2875449 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)
// Alternative version using traverse_
def charLineCount2[F[_] : Foldable](text: F[Char]) =
text.traverse_[({type λ[x] = State[(Int, Int), x]})#λ, Unit](a =>
state { case (chars, lines) =>
((chars + 1, lines + (a == '\n').fold(1, 0)), ())
}) ~> (0, 0)
println(charLineCount2("the cat in the hat\n sat on the mat\n".toList)) // (35, 2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment