[Haskell-cafe] Thompson's Exercise 9.13
Hamilton Richards
ham at cs.utexas.edu
Tue Apr 12 12:26:34 EDT 2005
Here's a solution:
> init :: [a] -> [a]
> init xs = tail (foldr keep [] xs)
> where
> keep :: a -> [a] -> [a]
> keep x [] = [x]
> keep x [y] = [x,x]
> keep x (y:z:zs) = x:x:y:zs
--Ham
At 3:44 PM +0900 2005/4/10, Kaoru Hosokawa wrote:
>I've been working through Thompson's exercises and got to one I
>could not solve. It's Exercise 9.13. This is where I need to define
>init using foldr.
>
> init :: [a] -> [a]
> init "Greggery Peccary" ~> "Greggary Peccar"
>
>This is as far as I got:
>
> init xs = foldr left [] xs
>
> left :: a -> [a] -> [a]
> left x [] = []
> left x1 : (x2 : xs) = x1 : (left x2 xs)
>
>But this returns [] and doesn't work. I can't get "left" to know
>that it is working with the rightmost element. It just throws away
>every element when its right hand side is empty.
>
>I found a solution that works for Strings, but I am looking for a
>more general solution. This exercise may yet again be one of those
>that is difficult to solve with my current knowledge of Haskell, but
>I'm asking anyway.
>
>--
>Kaoru Hosokawa
>khosokawa at gmail.com
>
>_______________________________________________
>Haskell-Cafe mailing list
>Haskell-Cafe at haskell.org
>http://www.haskell.org/mailman/listinfo/haskell-cafe
--
------------------------------------------------------------------
Hamilton Richards, PhD Department of Computer Sciences
Senior Lecturer The University of Texas at Austin
512-471-9525 1 University Station C0500
Taylor Hall 5.138 Austin, Texas 78712-0233
ham at cs.utexas.edu hrichrds at swbell.net
http://www.cs.utexas.edu/users/ham/richards
------------------------------------------------------------------
More information about the Haskell-Cafe
mailing list