Search code examples
stringhaskellreverse

how to write an reversed words function in haskell


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


Solution

  • 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