4
votes

What is wrong in my code:

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

3 Answers

2
votes

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.

2
votes

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".

1
votes

"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.