[Haskell-beginners] defining 'init' in terms of 'foldr'
Chaddaï Fouché
chaddai.fouche at gmail.com
Sun Dec 5 19:04:27 CET 2010
On Sun, Dec 5, 2010 at 3:51 PM, Hein Hundal <hundalhh at yahoo.com> wrote:
> I am trying to understand the differences between two
> different solutions to the problem of expressing init in
> terms of foldr.
>
> The two solutions are called heinInit and chaddiInit.
> The heinInit does not work on infinite lists. The
> chaddiaiInit function does work on infinite lists.
>
>
> heinInit v = fromJust $ foldr f Nothing v
> where
> f a Nothing = Just []
> f a (Just v) = Just (a:v)
>
>
> chaddaiInit v = fromJust $ foldr f Nothing v
> where
> f x xs = Just (case xs of Nothing -> []; Just ys -> x:ys)
>
> <<snip>>
>
> And it just keeps going. Is this the right idea? Are my
> "traces" a reasonable estimate of how Haskell
> evaluates those expressions?
Pretty good :-)
Another way to see it is that my solution provides information
earlier, in yours f needs to know whether its second argument was
Nothing or Just before it returns any information on its result, in
mine f start by "saying" it is a Just something even before it
examines its arguments. Using traces like you just did is the best way
to get reliable results (and you'll be able to run them in your head
with a bit more experience), but having intuition on the degree of
laziness of a function can help too. Most of the time it is better to
start out as lazy as possible (a good trick is to see if it will work
on infinite data structure), with experience you'll recognize the
points where strictness is needed instead.
--
Jedaï
More information about the Beginners
mailing list