[Haskell-beginners] defining 'init' in terms of 'foldr'

Daniel Fischer daniel.is.fischer at googlemail.com
Sat Dec 4 23:48:03 CET 2010


On Saturday 04 December 2010 23:20:51, Paul Higham wrote:
> Not sure if this thread is still active but I also struggled with this
> same exercise.  I offer the following solution as a thing to shoot at:
>
> myInit :: [a] -> [a]
> myInit ys = foldr snoc [] $ (\(x:xs) -> xs) $ foldr snoc [] ys
> 	    where snoc = (\x xs -> xs ++ [x])

init === reverse . tail . reverse
only holds for finite lists, for infinite lists xs, reverse xs = _|_, but 
init xs = xs.
Also, it's inefficient, but that's not the point of the exercise.

>
> Note that snoc is defined at the top of the same page as the exercise
> in Simon's book.
>
> ::paul

Cheers,
Daniel



More information about the Beginners mailing list