Friday, March 21, 2008

When to use point-free style

I've often struggled with the question of when/whether to use point-free style. It can be dangerously addictive, especially in languages with syntactic support for it like Haskell. But it's notorious for creating dense and impenetrable code. Yesterday I linked to advice from the GHC community on when not to create needless abstractions, advice which could be applied when considering a point-free abstraction (man, does it ever take self-restraint not to go wild with the puns here).

The reason why pointful style can be so helpful is it allows us to think about the definition of a computation in terms of particular examples. For any number, let's call it x, ... This is also why set comprehensions in math, and consequently list comprehensions in programming languages, are so approachable: they describe a set by appeal to representative examples.

I think the key to successfully using point-free style is when you want to treat a function itself as a single data point. For example, if you're sorting a list with some comparison function, you don't want to have to drop down a level of abstraction to think about the individual pairs of elements being compared; you just want to think about the comparison function (like "numeric" or "reverse alphabetical") as the object of your attention.

5 comments:

Unknown said...

Thanks Dave, this is a clear perspective which resonates with me immediately. It leaves open differences of personal interpretation of which functions should be viewed as a single data point, which I've never had the pleasure of debating since it was never put in those terms. Of course, for algebraic manipulations you want to push symbols around without thinking about the meaning of intermediate steps, and point-free seems helpful for this.

Paul Steckler said...

When taking university examinations, I always programmed in a point-free style. That is, I rarely got any points for my botched answers!

-- Paul

Pseudonym said...

Ye have heard it said in the past: "Magic numbers" must be given names commensurate with their semantic intent.

Verily I say unto you: Intermediate values with no semantic intent do not need names.

I was talking about this with Tom Conway the other day. He thinks this is the #1 difference between functional and logic programming. Logic programming is centred around the concept of the "logic variable", which means that even the most useless values need to be given variable names.

offby1 said...

So .. uh .. what _is_ this here "point-free style", anyway? 0.01 seconds of searching on Wikipedia yielded nothing ...

Dave Herman said...

Google does better than Wikipedia on this one. First hit is from the Haskell wiki:

http://www.haskell.org/haskellwiki/Pointfree