lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On Sat, Dec 5, 2009, steve donovan wrote:
> Most of us like to read from left to right, as a chain of operations.
> Functional people have a larger stack than most, so they're used to
> everything being prefix ;)
> ...
> numbers:filter(odd):map(square)

Functional programmers read left to right too.  The difference is
functional programmers read from a "top-down" perspective, whereas
imperative programmers read "bottom-up".  Imperative programmers often
think of a program as a chain of commands that manipulate values.  A
functional programmer thinks of a program as the composition of
smaller programs.

bottom-up interpretation:
   Start with a list of numbers, filter the odd values, and with the
list of odds, square each value.

top-down interpretation:
   square each value of a list of odds

and so the Haskell programmer would write:
   map square . filter odd

I find bottom-up easier to write and top-down easier to read and
understand.  When reading programs in the top-down style, you don't
concern yourself with the details until you have a high-level
understanding of the intent of the program.  In Haskell, I frequently
write programs bottom-up and then factor them until they are top-down.
 The top-down program tends to be a better form for further factoring,
because as soon as the code is point-free, you see all the places
where your code is coincidentally a perfect match with library
definitions.  You then swap out your own code with calls to the
library code, and go home early because you don't have to add any
documentation or tests!  :-)

Bird's Sudoku solver is an outstanding example of a program that is
easy to learn and understand because it is written in the top-down
style and in point-free notation:

http://www.cs.tufts.edu/~nr/comp150fp/archive/richard-bird/sudoku.pdf

-Greg