Hi! I'm new to Haskell and FP so i've got some problems. I wrote this code : getNr :: Int -> Int getNr x = do putStrLn ("enter " ++ x ++ " number:") nr <- getLine return nr And when I try to load it to GHCi I get an error (there is also plenty of others but they look the same): couldn't match Int against t t1 Help needed.
Szymon Ząbkiewicz wrote:
Hi! I'm new to Haskell and FP so i've got some problems. I wrote this code :
getNr :: Int -> Int getNr x = do putStrLn ("enter " ++ x ++ " number:") nr <- getLine return nr
And when I try to load it to GHCi I get an error (there is also plenty of others but they look the same):
There are several problems with this code: 1. You are using (++) to concatenate strings and the value x, which is of type Int. Use 'show' to convert numbers to strings. 2. The result type of getNr is Int, but the body of the function is a do expression, which is always a monadic value. Since you use the input/output operations putStrLn and getLine, the type of the function must be Int -> IO Int 3. The return value of getLine is a string, but you try to return it from the function, which (see 2) has a return value of IO Int. Use 'read' to convert the string to an integer value. HTH, Martin
haskell-cafe@haskell.org is usually a better venue for these sorts of questions. People there love helping people learn Haskell.
And when I try to load it to GHCi I get an error (there is also plenty of others but they look the same):
couldn't match Int against t t1
This error occurs because you provided a bad type signature, confusing yourself and triggering the type checker to correct you. Sometimes you can write code and if it compiles you can run ghci and try :t function and it will tell you the right type of the function. You might read http://haskell.org/haskellwiki/Introduction_to_IO and http://www.haskell.org/hawiki/ThatAnnoyingIoType There are (strange) reasons Haskell is the (strange) way it is. With patience (strange) things will make (strange) sense. Good luck! Jared. -- http://www.updike.org/~jared/ reverse ")-:"
participants (3)
-
Jared Updike -
Martin Grabmueller -
Szymon Ząbkiewicz