[Haskell-cafe] Reversing a string of words: C# v Perl V Ruby v
bjpop at csse.unimelb.edu.au
Mon Dec 11 22:20:15 EST 2006
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
>> 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
= revAcc (reverse str) 
revAcc  acc = acc
revAcc (x:xs) acc
| isSpace x = acc ++ (x : revAcc xs )
| otherwise = revAcc xs (x : acc)
More information about the Haskell-Cafe