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

Michael Mossey mpm at alumni.caltech.edu
Mon May 11 10:13:36 EDT 2009


In S. Thompson's book, problem 9.13 asks us to define 'init' in terms of 
foldr. I was baffled at first because I didn't see a natural way to do 
this. It would look something like

init xs = foldr f initialValue xs

where f would cons on each character except the rightmost.

f <when passed rightmost char> b = []
f <when passed any other char a> b = a : b

How does f "know" when it is passed the first character? initialValue has 
to signal this somehow. On #haskell, one person suggested doing it with 
some post-processing:

init xs = snd $ foldr f (True,[]) xs
   where f _  (True,_)  = (False,[])
         f a  (False,b) = (False,a:b)

I had an idea. If the initial value is the entire list, then its length can 
function as the "signal" that we are dealing with the rightmost char. This 
requires no post-processing:

init xs = foldr f xs xs
    where f a b | length b == length xs = []
                | otherwise = a:b

These seem contrived. I wonder if there is a more natural solution that 
Thompson had in mind. Any comments?

-Mike



More information about the Beginners mailing list