... until the collector arrives ...

This "blog" is really just a scratchpad of mine. There is not much of general interest here. Most of the content is scribbled down "live" as I discover things I want to remember. I rarely go back to correct mistakes in older entries. You have been warned :)

2009-08-29

Functional Programming Interview Question

I was reading a blog on fsharp.it that concerned a functional programming interview question. The challenge was to write a Haskell program that count occurrences of words in a text file. The blog posting exhibited an F# program to solve the problem, and briefly spoke to the comparison between functional and imperative style.

From time to time I like to tackle these toy problems in Mathematica. Mathematica is neither functional nor imperative, but rather is based upon pattern transformations. My solution to the programming problem in Mathematica was this:

{
  Import["http://www.starling-software.com/employment/input.txt", "Lines"],
  "NUMBERS",
  {"NUMBERS" -> {}, "ANIMALS" -> {}}
} //. {
  {{}, _, cs_} :> (cs /. (a_ -> b_) :> (a -> Tally@Sort@b)),
  {{c_, ws___}, _, cs:{___, c_ -> _, ___}} :> {{ws}, c, cs},
  {{w_, ws___}, c_, {cs1___, c_ -> {seen___}, cs2___}} :> {{ws}, c, {cs1, c->{w, seen}, cs2}}
}

The output from this code is:

{NUMBERS->{{one,2},{seven,1},{six,2},{three,2},{two,1}},ANIMALS->{{cow,1},{horse,2},{moose,1},{sheep,1}}}

This code uses an idiom in Mathematica that, without getting into details, repeatedly transforms an initial state until a desired final state is reached. If you know the idiom, the transformation is expressed fairly directly. If you don't know the idiom, the code is gibberish and looks like I'm trying to program without using identifiers.

All of this raises interesting questions about conciseness in programming. Functional code (and transformation code) is often radically shorter than an imperative equivalent. However, readability can suffer drastically, especially if the reader has not internalized the idioms used. It is going to be interesting to see how the current wave of interest in functional languages impacts the mainstream.

Blog Archive