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

Andrew Savige ajsavige at yahoo.com.au
Sun Dec 10 06:50:38 EST 2006

Recently, the C# programmers at work have been asking job
applicants to write a function to reverse a string of words.
For example, given an input string of:

 "  one   two three four    "

the function should produce:

 "four three two one"

That is, the input string reversed word by word, with a single
space between each word and with no leading or trailing space.
(You may assume that the input string consists only of alphabetic
characters, spaces and tabs).

A popular C# approach goes something like:

 private static string reverseWords(string str) {
     string[] words = Array.FindAll<string>(str.Split(
                      new char[] {' ','\t'}),
                      delegate(string s) {
                         return !String.IsNullOrEmpty(s); });
     int i = words.Length - 1;
     if (i < 0)
         return String.Empty;
     StringBuilder sb = new StringBuilder(words[i]);
     while (--i >= 0)
         sb.Append(' ').Append(words[i]);
     return sb.ToString();

Though the C# programmers seem happy enough with this solution,
it's a bit too verbose for my personal taste. For cheap thrills,
I'd like to show them some solutions to their little problem in
other, er, less verbose languages.

In Perl, I have:

 sub reverseWords {
     join ' ', reverse split(' ', shift)

In Ruby:

 def reverseWords(str)
     str.split(' ').reverse.join(' ')

Finally, and please don't laugh, in Haskell (GHC):

 reverseWords :: String -> String
 reverseWords xs = (concat (intersperse " " (reverse (words xs))))

which does appear to work correctly. However, I would like to do
justice to Haskell as a language -- and given that my clumsy
Haskell is not written in expert style -- I'm hoping that someone
on this list might offer a better, faster, or more idiomatic
Haskell solution to this little problem.


Send instant messages to your online friends http://au.messenger.yahoo.com 

More information about the Haskell-Cafe mailing list