Reputation:
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?
Upvotes: 2
Views: 116
Reputation: 476584
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()
Upvotes: 2