couldn't match expected type [a0] with actual type IO ()

前端 未结 3 1854
梦毁少年i
梦毁少年i 2021-01-13 21:00

What is wrong in my code:

insertValue file x = 
    if x == \"10\" then \"ok\"
    else do putStrLn \"Error\"; file
相关标签:
3条回答
  • 2021-01-13 21:43

    "ok" is of type "String" while the "else" clause is of type "IO ()". In Haskell "if" is an expression, so they have to match.

    Its difficult to help more without knowing what you are trying to do.

    0 讨论(0)
  • 2021-01-13 22:00

    In an if..then..else expression, both branches have to have the same type.

    One branch is:

    "10" :: String
    

    The other branch is:

    do putStrLn "Error"; file :: IO ??
    

    Since I'm not sure what you're trying to do (and the compiler isn't sure either), I don't know how to correct the code.

    0 讨论(0)
  • 2021-01-13 22:01

    You need to use return :: a -> IO a to "lift" your strings into IO String:

    insertValue file x = 
        if x == "10"
          then return "ok"
          else do putStrLn "Error"
                  return file
    

    But are you sure you don't want to call putStrLn "ok" (instead of return "ok") and return a Maybe value? Otherwise you are returning file or "ok" and your caller could never determine if there was an error when calling insertValue on a file named "ok".

    0 讨论(0)
提交回复
热议问题