Kernighan & Ritchie word count example program in a functional language

Posted by Frank on Stack Overflow See other posts from Stack Overflow or by Frank
Published on 2012-04-07T01:25:25Z Indexed on 2012/04/07 23:29 UTC
Read the original article Hit count: 245

I have been reading a little bit about functional programming on the web lately and I think I got a basic idea about the concepts behind it.

I'm curious how everyday programming problems which involve some kind of state are solved in a pure functional programing language.

For example: how would the word count program from the book 'The C programming Language' be implemented in a pure functional language?

Any contributions are welcome as long as the solution is in a pure functional style.

Here's the word count C code from the book:

#include <stdio.h>

#define IN  1 /* inside a word */
#define OUT 0 /* outside a word */

/* count lines, words, and characters in input */
main()
{
  int c, nl, nw, nc, state;

  state = OUT;
  nl = nw = nc = 0;
  while ((c = getchar()) != EOF) {
    ++nc;
    if (c == '\n')
      ++nl;
    if (c == ' ' || c == '\n' || c = '\t')
      state = OUT;
    else if (state == OUT) {
      state = IN;
      ++nw;
    }
  }

  printf("%d %d %d\n", nl, nw, nc);
}

© Stack Overflow or respective owner

Related posts about haskell

Related posts about functional-programming