Monday, February 9, 2009

splitWith using foldr

Real World Haskell's chapter 4 has the following problem:

Write a function splitWith that acts similarly to words, but takes a predicate and a list of any type, and splits its input list on every element for which the predicate returns False.

I really wanted to do this with a foldr. The problem just seems to call for fold. Here is my attempt. I put a bit extra there to make sure I handle things I didn't like.

I feel dirty.

3 comments:

elzurk said...

Darn blogging engine can't pretty print Haskell. Spacing looks WRONG :(

Aluink said...

splitter i s@(ac:acs) | (f i) = ((i:ac):acs)
| (null ac) = s
| otherwise = []:s

elzurk said...

A new version, using the s@ syntax, and using dropWhile instead of the explicit recursion to chop the leading badness can be found at: http://gist.github.com/62421