Reputation: 175
I am trying to write a function that gets multiple string inputs and terminates on an empty line ('\n') I have following
getLines :: IO [String]
getLines = do x <- getLine
if x == ""
return ()
else do xs <- getLines
return (x:xs)
it fails to compile saying there is something wrong with the if statement
Ideally I want to to work like this
getLines
Apple
Bird
Cat
(enter is pressed)
Output: ["Apple","Bird","Cat"]
Upvotes: 2
Views: 2353
Reputation: 55029
You need then
after if
, and ()
(empty tuple) should be []
(empty list). In if
, the then
and else
need to be indented as well if they’re on separate lines, because if then else
is an operator, and the compiler needs to know that the expression continues. Your indentation needs to be adjusted so that everything is indented more than the leading do
:
getLines :: IO [String]
getLines = do x <- getLine
if x == ""
then return []
else do xs <- getLines
return (x:xs)
Or everything is indented more than the line containing the leading do
:
getLines :: IO [String]
getLines = do
x <- getLine
if x == ""
then return []
else do
xs <- getLines
return (x:xs)
As a matter of style, you can also use null x
instead of x == ""
.
Upvotes: 7
Reputation: 62848
This is nearly right.
You need a then
after your if
. You may also need to change the indentation slightly, so that everything is indented as far as the x
rather than the do
. I think that should just about do it.
Upvotes: 1