6

I am trying to make a program that reads a number given by a user and then prints it. the number has to be an integer when I print it, but this code gives me a parse error:

main = do
{
       putStrLn "Please enter the number"
       number <- getLine
       putStrLn "The num is:" ++ show (read number:: Int)
}
3
  • What's the actual error? Commented Jan 16, 2012 at 5:53
  • 3:8: Parse error in pattern: putStrLn Commented Jan 16, 2012 at 5:53
  • That was my first question too, but you can easily guess just by looking at the code, so it's okay :) Commented Jan 16, 2012 at 5:54

2 Answers 2

10

If you use brackets in your do statement, you have to use semicolons. Also, the last line should be putStrLn $ "The num is:" ++ show (read number :: Int)

So you have two options:

main = do
{
   putStrLn "Please enter the number";
   number <- getLine;
   putStrLn $ "The num is:" ++ show (read number:: Int)
}

or:

main = do
   putStrLn "Please enter the number"
   number <- getLine
   putStrLn $ "The num is:" ++ show (read number:: Int)

Almost all of the code I've seen uses the second version, but they are both valid. Note that in the second version, whitespace becomes significant.

Sign up to request clarification or add additional context in comments.

4 Comments

can you please tell me how i can read this number as integer directly or how to convert it afterwards
You can just use readLn :: IO Int instead of getLine. In this snippet, there is not enough information to infer it's a number without specifying it somewhere; if you actually did some numeric stuff with it, you'd be able to use readLn by itself.
suppose the user inputs 10 and then compiler should ask user to input 10 numbers and then form a list. how can that be done using sequence?
I think you're best off asking something unrelated like that as a separate question.
1

Haskell recognizes the Tab character and your program could be failing because of that. If you're using Tabs, change them to whitespaces.

1 Comment

That does often cause trouble, but it wasn't the problem here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.