Express What, not How.

Michael Chermside mcherm at mcherm.com
Wed Oct 15 19:46:38 EDT 2003


gt5163b at prism.gatech.edu (Brian McNamara!) wrote previously:
|   nat :: Parser Int
|   nat = do {c <- digit; return charToInt c}
|         `chainl1` (return \x y -> 10*x+y)
|If I understand you correctly, you would insist I write something like
|   nat :: Parser Int
|   nat = do {c <- digit; return charToInt c}
|         `chainl1` combineDigits
|            where combineDigits = return \x y -> 10*x+y

David Mertz writes:
> Even if looking through your library documentation to find the name
> 'combineDigits' is the one used is extra work, it's much less work for
> other programmers to read your definition of 'nat' if it uses a
> descriptive name.  (admittedly, for a silly and trivial function, the
> difference is small; but I think the stipulation applies that
> 'combineDigits' is a proxy in the discussion for a more complex
> real-world function).

No, I think that what Brian was saying was that in this exact case,
naming a function like combineDigits is worse than useless. It forces
the programmer to memorize the name.

To me, I find the string "\x y -> 10*x+y" to be MORE readable than
the string "combineDigits". Admitedly, it is one character longer,
but unlike "combineDigits", it states CLEARLY and UNAMBIGUOUSLY
exactly what is being done.

If you had a complex 5-line function, then I would prefer the name
every time. But sometimes a thing is so simple that it's EASIER to
write it out.

Hmm... what's another example? We laud a language like Python for
having only a few simple constructs (one branch statement, two kinds
of loops, assignments, function and class definitions, plus a few 
others) which are combined to create any program imaginable. If there
were 20 different kinds of loops instead of 2, it would not make
the language more expressive, or more readable... it would probably
be LESS readable. There would just be too much unnecessary 
vocabulary to keep track of.

Similarly, when defining a program, it's important to maintain the
proper level of abstraction. Sometimes, it's better to write out
a function anonymously if it's (1) has limited or no re-use value,
(2) does not represent an important concept which needs to be
identified, and (3) is short enough to be groked as a unit.

-- Michael Chermside






More information about the Python-list mailing list