
On 12/12/2006, at 11:13 AM, Brandon S. Allbery KF8NH wrote:
On Dec 11, 2006, at 18:48 , Steve Downey wrote:
the typical good solution to this problem in c or c++ is to use a string reverse function on the entire buffer, then re-reverse each word. this leaves multiple spaces correctly embedded in the larger string. that approach, of course, won't work in haskell, since it relies on updates. but if the challenge includes transforming "one two three four " into " four three two one", how could this be done?
Off the top of my head, the C++ one translates to:
*Main> concatMap reverse . groupBy (\l r -> (l == ' ') == (r == ' ')) . reverse $ "one two three four " " four three two one"
There are almost certainly more idiomatic ways to do it, but I'm still learning.
Perhaps something like this is close to the algorithm you describe: import Data.Char (isSpace) rev :: String -> String rev str = revAcc (reverse str) [] where revAcc [] acc = acc revAcc (x:xs) acc | isSpace x = acc ++ (x : revAcc xs []) | otherwise = revAcc xs (x : acc) Cheers, Bernie.