Friday, July 27, 2012

FP languages are expressive

I've spent this week learning functional programming using two languages from opposite ends of the FP space: Haskell, an uncompromisingly functional language, and Scala, which mixes in some OO concepts with an eye to inter-operation with Java.

The central argument for FP is expressivity. Because of the power of the tools FP languages offer, you are supposed to be able to get a lot done with only a few lines of code.

To test this claim, I used both languages to implement a program from The Practice of Programming by Kernighan and Pike. The program reads in a file of text, generates a Markov-chain transition map from it, and then uses the map to produce random text. The authors implemented this program in several major languages, and found that the amount of code needed varied significantly: the C program was 150 lines, the Java was 105, and C++ clocked in at 70 lines.

Both Haskell and Scala did better than this. The Haskell program was 45 lines, and Scala did even better, at 41(!).

As far as I can tell, the FP enthusiasts' claim of greater expressivity is right on the money.

No comments:

Post a Comment