[Haskell-beginners] Re: folds again -- myCycle

Daniel Fischer daniel.is.fischer at web.de
Wed Mar 18 07:45:38 EDT 2009


Am Mittwoch, 18. März 2009 12:19 schrieb Will Ness:
> Bas van Dijk <v.dijk.bas <at> gmail.com> writes:
> > On Sun, Mar 15, 2009 at 7:35 PM, Will Ness <will_n48 <at> yahoo.com> 
wrote:
> > > which is then just rewritable as:
> > >
> > > myCycle xs = ys where ys = foldr (:) ys xs
> > >
> > > or (arriving at the same result)
> > >
> > > myCycle xs = foldr (:) (myCycle xs) xs
> >
> > Note that, because 'ys' only has to be calculated once, GHC makes the
> > most efficient code for the former one. In the latter 'myCycle xs' has
> > to be calculated each time 'xs' runs empty.
>
> Actually my point was, that
>
> " I find that "where" rewrites are easier to comprehend for me,
>   more often than not. :) "

Of course a matter of personal preference, but I tend to prefer where clauses, 
too, in general. However, my preferred layout is

some code
      where
        local declarations

I deeply loathe not having the where on a separate line :-/

>
> "  myCycle xs = ys where ys = foldr (:) ys xs "
>
> which should be exactly as the one with the let.
>
AFAIK,

myCycle1 [] = []
myCycle1 xs = let ys = foldr (:) ys xs in ys

and

myCycle2 [] = []
myCycle2 xs = ys
      where
	ys = foldr (:) ys xs

are compiled to exactly the same code. In GHC, I think the first thing that 
happens to myCycle2 is that it's rewritten to myCycle1.

What matters if whether you give a name to the result to get it shared or not.



More information about the Beginners mailing list