Thursday, 1 January 2009

Functional Programming Patterns.

Roundabout presents a set of patterns for writing recursive programs.

  • Structural Recursion - use recursion to traverse inductively defined data structures (e.g. list ortree)

  • Interface Procedure - use a helper method to adapt a function call if you need an extra argument

  • Mutual Recursion - use multiple recursive functions to traverse inductively defined data structures where elements in the data structure are also inductively defined

  • Accumulator Variable - use an additional parameter to carry calculations through recursion

  • Syntax Procedure - extract methods that mean something rather than accessing raw members of data structures (e.g. for trees written as lists use (lhs foo) instead of (first foo)

  • Local Procedure - use anonymous methods to hide details from the outside world

  • Program Derivation - inline code if you want more performance

The relationship between patterns and refactoring has already been written about ("Refactoring to Patterns"). In this case the relationships are quite clear.

Not all of the patterns are directly applicable to all languages. For example, Program Derivation is unwarranted for Lisp type languages because macros provide all those capabilities. I guess that's another one for the design patterns are a weakness of the language meme.