[Haskell-beginners] Re: Iterating through a list of char...

Brent Yorgey byorgey at seas.upenn.edu
Thu Apr 29 14:00:47 EDT 2010


On Thu, Apr 29, 2010 at 10:48:15AM -0400, matthew coolbeth wrote:
> I understand that higher-order functions  are incredibly powerful, and that
> you can do essentially anything you might ever want while using only 'map'
> and 'foldl'.
> 
> However,  I have trouble believing that even experienced programmers wold
> find such HOF-oriented code to be more readable than Mr Akgun's solution:
> 
> foo :: (a -> a -> a) -> [a] -> [a]
> foo f (x:y:rest) = f x y : foo f (y:rest)
> foo f _ = []
> 
> It seems to me that 'foo', as defined here, is a direct restatement of the
> original program specification (the english one).  Basically no translation
> required.
> 
> If anyone here is enough of a veteran to prefer a map/fold implementation of
> this spec,  I would be interested to hear about the thought processes you
> undertake when writing such code.

Instead of map/fold, I would absolutely prefer an implementation in
terms of zipWith:

> foo f xs = zipWith f xs (tail xs)

or perhaps

> foo f xs = zipWith f (i:xs) xs

where i is some sort of initial value.  It is immediately clear to me
what this code does (match up "staggered" versions of xs, and zip
them up with the function f).  On the other hand, the solution you
cited above takes me a a little time to read and digest, since it is
much more "low-level".  Consider:

> foo :: (a -> a -> a) -> [a] -> [a]
> foo f (x:y:rest) = f x y : foo f (x:rest)
> foo f _ = []

This version is slightly (and crucially) different than the original.
Can you spot how?  I can easily imagine typing this wrong version by
accident when trying to implement foo.  And if it's that easy to make
a silly but dramatic change, it must take a correspondingly large
amount of energy to make sure you have understood all the details when
reading the code.  On the other hand, I can't think of very many ways
to modify the zipWith implementation; there are far fewer pieces to
get right and/or understand.

Using higher-order functions and recursion combinators can be a
strange discipline at first, but with practice it frees you to forget
about details and think about things at a higher level.

-Brent


More information about the Beginners mailing list