-
-
Save bmjames/2875449 to your computer and use it in GitHub Desktop.
wordcount example in scalaz using State monad
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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