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

Daniel Fischer daniel.is.fischer at web.de
Thu Apr 29 14:04:28 EDT 2010


Am Donnerstag 29 April 2010 16:48:15 schrieb matthew coolbeth:
> 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'.

No, you absolutely need foldr 8)
(and foldl' is usually the better choice than 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.

foo f xs = zipWith f xs (drop 1 xs)

is equally readable - and that's it, I think; with experience, HOF-oriented 
code becomes as readable as the direct recursive code.

>
> 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.

No thought process, one just sees that it's a map/fold/... (after one has 
spent enough time looking for folds and such). Often before one sees the 
direct implementation.

Do I prefer a map/fold/scan/zipWith implementation of such a spec?
Yes and no.
There's one definite advantage to coding (and thinking) in higher order 
functions/combinators. It helps identifying recurring patterns and then you 
write the combinator for that pattern. Once. You need only prove the 
correctness once. After that, you need only worry about the correctness of 
the combining function.

>
> Thanks.
>
> On Thu, Apr 29, 2010 at 10:22, David Virebayre
> <dav.vire+haskell at gmail.com<dav.vire%2Bhaskell at gmail.com>
>
> > wrote:
> >
> > On Thu, Apr 29, 2010 at 3:52 PM, jean verdier <verdier.jean at gmail.com>
> >
> > wrote:
> > > I may have missed it in this thread, but if not, why didn't anyone
> > > suggest:
> > >
> > > trans []         = []
> > > trans [x]        = [x]
> > > trans ('a':_:xs) = 'a' : 'A' : trans xs
> > > trans     (x:xs) =        x  : trans xs
> >
> > While as a beginner (I still am !) I would come up with a solution
> > like this one, on the long run it helps trying to solve those problem
> > with maps, folds, filters, and zips: Eventually, you'll find the code
> > more readable, easier to write,  and there's perhaps a better chance
> > that it can be optimised by ghc.
> >
> > David.



More information about the Beginners mailing list