Skip to content

Instantly share code, notes, and snippets.

@willtim
Created August 16, 2012 16:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save willtim/3371468 to your computer and use it in GitHub Desktop.
Save willtim/3371468 to your computer and use it in GitHub Desktop.
Purely functional version of Kernighan and Ritchie’s wc program
/**
* @author willtim
* Purely functional version of Kernighan and Ritchie’s wc program
*
* #include <stdio.h>
* #define IN 1 /* inside a word */
* #define OUT 0 /* outside a word */
* int blank(int c) {
* return ( c==’ ’ || c==’\n’ || c==’\t’);
* }
* /* count words in input */
* main() {
* int c, nw, state;
* state = OUT;
* nw = 0;
* while ((c = getchar()) != EOF) {
* if (blank(c)) state = OUT;
* else if (state == OUT) {
* state = IN;
* ++nw;
* }
* }
* printf("%d\n", nw);
* }
*/
object WordCount {
def wc(s: String): Int = s.foldLeft((0, false)) {
(t: (Int, Boolean), c: Char) => t match {
case (n, _) if isBlank(c) => (n, false)
case (n, true) => (n, true)
case (n, false) => (n+1, true)
}}._1
def isBlank(c: Char) = c==' ' || c=='\n' || c=='\t'
def main(args: Array[String]) {
println {
wc(" the quick brown fox ")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment