Haskell IO: Couldn't match expected type `IO a0' with actual type

19,889

username is a String, but promptUsername is an IO String. You need to do something like:

username <- promptUsername
let entry = Entry username "somepassword"
persist entry
Share:
19,889
Lauri Lehmijoki
Author by

Lauri Lehmijoki

Programmer

Updated on June 26, 2022

Comments

  • Lauri Lehmijoki
    Lauri Lehmijoki almost 2 years

    I am new to Haskell, and I try to understand how to do IO correctly.

    The following works ok:

    main = do
      action <- cmdParser
      putStrLn "Username to add to the password manager:"
      username <- getLine
      case action of
        Add -> persist entry
          where
            entry = Entry username "somepassword"
    

    Whereas the following results in compilation error:

    main = do
      action <- cmdParser
      case action of
        Add -> persist entry
          where
            entry = Entry promptUsername "somepassword"
    
    promptUsername = do
      putStrLn "Username to add to the password manager:"
      username <- getLine
    

    The error is here:

    Couldn't match expected type `IO b0' with actual type `[Char]'
    Expected type: IO b0
      Actual type: String
    In the expression: username
    [...]
    

    What is going on here? Why the first version works, while the second one does not?

    I know that in Stack Overflow there are a few similar questions like this, but none of them seemed to explain this problem to me.