Home > Enterprise >  how to write an reversed words function in haskell
how to write an reversed words function in haskell

Time:01-18

Write a program that reads a text in an endless loop, every single word flipped over and then put back together as text. If the input is empty, the program should abort, stop. To do this, write a reverseWords::String -> String function that does the reversing is working.

for example:

reverseWords "Hello World, 123" -> "olleH ,dlroW 321"

my code

reverseWords :: String -> String 
reverseWords = unwords . reverse . words

doesnt work

CodePudding user response:

The function reverse reverses the entire list, so you are getting the words in the reverse order. What you want instead, is to reverse each element separately, which can be fixed with map:

reverseWords = unwords . map reverse . words

CodePudding user response:

If you need to preserve spacing characters other than ' ', then things get a little tricky. Fortunately, the split package can help.

import Data.List.Split
import Data.Char

reverseWords :: String -> String
reverseWords = concatMap reverse . split (whenElt isSpace)
  •  Tags:  
  • Related