folds in scala

Happy new year!

There's been several threads on the Scala list about syntax, and in particular a lot of hating on the /: and :\ methods as shorthands for foldLeft and foldRight. I understand the concerns about overuse of meaningless glyphs, but:

  • I think this concern is mostly misplaced in Scala, since operators translate straightforwardly into methods, so it's always obvious where to look for the definition;
  • and in any case I still like /: and :\ for folds.

Ricky Clarkson posts a defense of these methods, and I agree with him. In fact, I feel a little stronger. Martin's explanation closed the case for me months ago:

1. (z /: xs) (op) looks like an abbreviation of a left leaning tree
with a `z' on the lower left end (at least to me). I.e. something like

    /    \
   op    x1
  /  \
 z   x0

That's the tree I always draw when I explain fold left.

2. (z /: xs) has the operands in the ``right'' order.

I love the fact that the direction of the fold is clear. Even after years of work, I still have trouble remembering which direction foldLeft and foldRight really go, but with the symbol, it's obvious. I do have to remember that these mean "fold", but that's the easy part. As final evidence, I still can't tell you whether /: is foldLeft or foldRight without scratching my head, but I know what it does, and that's what counts.

So I hope /: and :\ stay in the standard library. On the other hand, I do hope to see a future where IDEs can selectively unroll higher-order functions into explicit recursive definitions or loops, because I do agree that sometimes it's more clear. This is not a long way off. Selective inlining similar to Fluid AOP is easily achievable today, and in addition to higher-order functions, it would make many common OO patterns much clearer. Consider, for example, an inlined view of a common visitor implementation. Selective inlining strikes exactly the right balance between clarity (when programming) and appropriate abstraction (in the underlying program). Plugin implementors take note: more of this, please!

Finally, it's unfortunate that /: and :\ don't really generalize to visually suggestive glyphs for folds over other data structures, such as trees. But folds over sequences are so common that it's still worth including them, and since any traversal of a data structure can be encoded as an Iterator, it's probably sufficiently general in any case.