[Haskell-beginners] This is problem 2, chapter 4 RWH

Daniel Fischer daniel.is.fischer at web.de
Wed Jan 21 21:02:42 EST 2009


Am Donnerstag, 22. Januar 2009 02:33 schrieb Michael Litchard:
> splitWith' :: (a -> Bool) -> [a] -> [[a]]
> splitWith' p x = case takeUntil p x of
>         [] -> []
>         x' -> subset : splitWith' p x''
>               where (subset, x'') = break p x'
>    where takeUntil :: (a -> Bool) -> [a] -> [a]
>          takeUntil p' = takeWhile q
>               where q x = not (p' x)
>
> It doesn't give me the right behavior though.
> It should work like this:
> splitWith' odd [2,2,1,4,4,3,6,6,5]
> [[2,2],[4,4],[6,6]]
> but it works like this instead
> [[2,2]]
>
> I'm pretty sure I modeled splitWith' on words, which is what the
> exercise indirectly suggests.
> Can someone help me step through this code to figure out what's wrong.
> It looks right to me.

takeUntil odd [2,2,1,4,4,3,6,6,5]
gives [2,2], so the second branch is taken, next break odd [2,2] is 
calculated. Since this list doesn't contain any odd numbers,
break odd [2,2] == ([2,2],[]), so subset = [2,2], x'' = [] and
subset : splitWith' p x'' reduces to [2,2] : splitWith odd [], which of course 
is [2,2] : [] = [[2,2]].
Your code never touches anything behind the first odd number. To rectify that, 
instead of takeUntil, you need a function which returns two parts, the 
initial segment of the list until the first odd number and the part following 
the first odd number (if there is any). Then your result would be 
(first part) : splitWith' p (second part). You already use the relevant 
function, albeit in the wrong place.

>
>
> Michael Litchard

HTH,
Daniel


More information about the Beginners mailing list