2

I want a program that takes lines and prints reverse when it encounters an empty line. This is my code.

back :: IO()
back = do
  line <- getLine 
  if (not $ null line) then do
  mapM_ putStrLn (reverse line)
  else return()

When I try to run this it gives an error.

* Couldn't match type `Char' with `[Char]'
      Expected: [String]
        Actual: [Char]
    * In the second argument of `mapM_', namely `(reverse line)'
      In a stmt of a 'do' block: mapM_ putStrLn (reverse line)
      In the expression: do mapM_ putStrLn (reverse line)
  |
6 |     mapM_ putStrLn(reverse line)
  |                    ^^^^^^^^^^^^

What is going wrong here?

Chris
  • 26,361
  • 5
  • 21
  • 42

1 Answers1

2

line is a String. Since you use mapM_ putStrLn, it expects a list of strings, so mapM_ putStrLn :: [String] -> IO ().

It is not entirely clear if you want to reverse each line, or the lines itself. In case of the former, you can work with:

back :: IO()
back = do
  line <- getLine 
  if not (null line) then do
    putStrLn (reverse line)
    back
  else return()

in case of the latter, you can use recursion, and first call back recursively, and then print the line:

back :: IO()
back = do
  line <- getLine 
  if not (null line) then do
    back
    putStrLn line
  else return()
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555