[Haskell-cafe] Why functional programming matters
Paul Johnson
paul at cogito.org.uk
Thu Jan 24 16:11:40 EST 2008
Simon Peyton-Jones wrote:
> 1. Small examples of actual code. The goal here is (a) to convey a visceral idea of what functional programming *is*, rather than just assume the audience knows (they don't), and (b) to convey an idea of why it might be good.
Here is one I came across in the last few days. I was reviewing some
code in Java, and it contained a function that looked through a list of
Foo instances for the latest update. I don't actually speak Java, but
it went something like this:
// Get the Foo that was most recently updated.
Foo latestUpdate (Iterator <Foo> iterator) {
long latestTimeSoFar = 0;
Foo latestFooSoFar = Null;
while (iterator.hasNext()) {
item = iterator.getNext();
if (item.updateTime > latestTimeSoFar) {
latestTimeSoFar = item.updateTime;
latestFooSoFar = item;
}
}
return latestFooSoFar;
}
This takes an iterator over some collection of Foos and finds the one
with the highest value of updateTime. 9 lines of code, or 12 with the
closing curly brackets.
In Haskell this is so short and obvious you probably wouldn't bother
declaring it as a function, but if you did, here it is:
-- Find the Foo that was most recently updated.
latestUpdate :: [Foo] -> Foo
latestUpdate foos = maximumBy (comparing updateTime) foos
Of course you could always write it in point-free format, but I think
that would be over-egging things.
Paul.
More information about the Haskell-Cafe
mailing list