Re: [Haskell-cafe] Thompson's Exercise 9.13

Am Sonntag, 10. April 2005 17:33 schrieben Sie:
On 2005/04/10, at 18:18, Daniel Fischer wrote:
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.
I cannot imagine how you could do it for Strings, but not for general lists. Mind sending me the code?
The code is here: http://wiki.pragprog.com/cgi-bin/wiki.cgi/ThompsonNineAnswersJD Look for 9.13 towards the bottom of the page.
It uses chr 0 as an end of string marker, and so this solution only works for Strings.
Unfortunately, Strings may contain '\0': *Init> finit "this doesn't\0quite\0work\0!" "this doesn't\NULquite\NULwor" so it doesn't work in all cases. The idea is nice, though: import Data.Maybe finit = catMaybes . foldr f [Nothing] . map Just where f x ys = case ys of [Nothing] -> [] _ -> x:ys will do fine.
-- Kaoru Hosokawa khosokawa@gmail.com
Cheers, Daniel

Am Sonntag, 10. April 2005 19:46 schrieb Daniel Fischer:
so it doesn't work in all cases. The idea is nice, though:
import Data.Maybe
finit = catMaybes . foldr f [Nothing] . map Just where f x ys = case ys of [Nothing] -> [] _ -> x:ys
will do fine.
Ooooops, only for nonempty lists!
Replace catMaybes with 'map (maybe (error "init of []") id)' and it'll work also for empty lists.
participants (1)
-
Daniel Fischer