Monday, February 12, 2007

Making Ruby Functional

I'm no expert at functional programming. I did a bit of LISP in college. Like you, I thought it was ugly. But I like FP anyway.

FP is supposed to be important because of higher-order functions and lazy evaluation, as they encourage modularity. And hell, who can argue with modularity?

But in Ruby, our most important tool for modularity is, um, modules (classes, objects). We're not fully FP. At a high level, we modularize using objects, and FP comes in at a tighter granularity, where its benefits are more limited -- but still important.

In Ruby's mixed environment, we can make our code simpler by using the higher order functional abstractions provided us (by Enumerable). There are as many "map"s in my code as "if"s. Make your own higher-order functions, even curried ones, if you like (though I rarely find the need).

We also make our code more expressive of intent. In FP, functions lack side effects. In other words, by asking a question, you want just the answer, not to change the state of the world in the process. Well, if what I want is an answer and not to be changing the state of the world, then expressing my intention using an FP style looks right. I'm declaring what I want. I see my code a week later and I know what I was doing. It's just laid out right: here's the goal, here's the starting point, and here are the steps that take me from the latter to the former.

%> my_result = 
starting_point.munged_once.and_again


Ruby makes this easy.

1 comment:

Philippe said...

thanks for the tip to use mixed fp and oo programming in ruby!