[Haskell-cafe] Reversing a string of words: C# v Perl V Ruby v Haskell

Brandon S. Allbery KF8NH allbery at ece.cmu.edu
Mon Dec 11 19:13:53 EST 2006


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.

-- 
brandon s. allbery    [linux,solaris,freebsd,perl]     allbery at kf8nh.com
system administrator [openafs,heimdal,too many hats] allbery at ece.cmu.edu
electrical and computer engineering, carnegie mellon university    KF8NH





More information about the Haskell-Cafe mailing list