1

I have this:

data SomeData = SomeData Int Int

getDataFromUser :: SomeData
getDataFromUser = do
{
    read (getLine)::SomeData;
}

This doesnt compile : Expected type String Actual type IO String

How I can fix it? I need this data deserialization...

1
  • The answers below are "more helpful" in the sense that they address the conceptual problem you have; however, you may also be interested in the "less helpful" fix, getDataFromUser :: IO SomeData; getDataFromUser = readLn. Commented Jan 13, 2012 at 20:30

2 Answers 2

9

You're trying to treat getLine as a String, but it's an IO String — an IO action that, when executed, produces a string. You can execute it and get the resulting value from inside a do block by using <-, but since getDataFromUser does IO, its type has to be IO SomeData:

getDataFromUser :: IO SomeData
getDataFromUser = do
  line <- getLine
  return $ read line

More broadly, I would recommend reading a tutorial on IO in Haskell, like Learn You a Haskell's chapter on IO; it's very different from the IO facilities of most other languages, and it can take some time to get used to how things fit together; it's hard to convey a full understanding with answers to specific questions like this :)

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

Comments

7

You need to read up more on how Haskell IO works and make sure you understand it.

A couple of points on your example. If you want to use read to deserialize to SomeData, you need to provide a Read instance for the type. You can use the default one:

data SomeData = SomeData Int Int deriving (Read)

Second: getLine is an IO action that returns a String, not a String; since read wants a String, this is the cause of your error. This is closer to what you want:

getDataFromUser :: IO SomeData
getDataFromUser = do str <- getLine
                     return (read str)

This can be simplified to the following, but make sure you understand the above example before you worry too much about this:

getDataFromUser :: IO SomeData
getDataFromUser = liftM read getLine

Comments

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.