[Haskell-cafe] Re: Is this a useful higher-order function, or should I RTFM?

Steven Huwig shuwig at columbus.rr.com
Fri Dec 3 14:03:23 EST 2004


On Dec 3, 2004, at 1:28 PM, Steven Huwig wrote:

> I am basically a newbie at Haskell, and have been experimenting with
> it where typically I would use Python.
...
> 2) Do unravel and ravel have any other practical uses on their own?
>    Looking at it, I think they could be used in a single function
>    of type f :: (a->Bool) -> ([a] -> [a]) -> [a] -> [a]
>    Can one get that function out of the Prelude in an easier manner 
> than
>    above? Is there a simpler way to get that functionality besides
>    composing ravel and unravel with a map in between?
>

(Bad form to self-reply, I know.) The answer to that question is yes.

--

mapGroups :: (a -> Bool) -> ([a] -> [a]) -> [a] -> [a]
mapGroups = mapGroups' []

mapGroups' :: [a] -> (a -> Bool) -> ([a] -> [a]) -> [a] -> [a]
mapGroups' acc _ _ [] = acc
mapGroups' acc p f z@(x:_)
     | p x = mapGroups' (acc ++ f part1) p f part2
     | otherwise = mapGroups' (acc ++ part1') p f part2'
     where (part1, part2) = span p z
           (part1', part2') = span (not . p) z

mapWords = mapGroups (not . isSpace)

initcap :: String -> String
initcap (c:cs) = toUpper c:[toLower c' | c' <- cs]

main = putStrLn (mapWords initcap "This\nis\t\ta test\n")

--

Now I can solicit your remarks yet again :)

-- Steven Huwig



More information about the Haskell-Cafe mailing list