Created
May 20, 2013 07:57
-
-
Save markus1189/5610943 to your computer and use it in GitHub Desktop.
This file contains 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._ | |
object CVersion { | |
def wc(cs: TraversableOnce[Char]): (Int,Int,Int) = { | |
var numLines,numWords,numChars = 0 | |
var inWord = false | |
cs.foreach { char => | |
numChars += 1 | |
if (char == '\n') numLines += 1 | |
if (char == ' ' || char == '\n' || char == '\t') { | |
inWord = false | |
} else if (inWord == false) { | |
inWord = true | |
numWords += 1 | |
} | |
} | |
(numChars, numWords, numLines) | |
} | |
} | |
object FunctionalVersion { | |
def test(b: Boolean): Int = if (b) 1 else 0 | |
def wc(cs: TraversableOnce[Char]): (Int,Int,Int) = { | |
def countChars(c: Char): Writer[Int,Char] = c.set(1) | |
def countLines(c: Char): Writer[Int,Char] = c.set(test(c == '\n')) | |
def countWord(c: Char): State[(Int,Boolean),Char] = for { | |
tuple <- get[(Int,Boolean)] | |
(n,inWord) = tuple | |
notBlank = !( c == ' ' || c == '\n' || c == '\t') | |
_ <- put(n + test(!inWord && notBlank),notBlank) | |
} yield c | |
val csList = cs.toList | |
val chars: Int = csList.map(countChars).sequenceU.run._1 | |
val lines: Int = csList.map(countLines).sequenceU.run._1 | |
val words: Int = csList.map(countWord).sequenceU.exec((0,false))._1 | |
(chars,words,lines) | |
} | |
} | |
object TestStrings { | |
val testString = """Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod | |
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim | |
veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea | |
commodo consequat. Duis aute irure dolor in reprehenderit in voluptate | |
velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat | |
cupidatat non proident, sunt in culpa qui officia deserunt mollit anim | |
id est laborum. | |
""" | |
} | |
object Main extends App { | |
import TestStrings._ | |
println(CVersion.wc(testString)) | |
println(FunctionalVersion.wc(testString)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment