Haskell IO example

haskell, io, monads

Solution

I've done two changes to the code.

- Fix the indentation -- remember that haskell is "space sensitive", so please make sure the code looks properly aligned

- Explicit type signatures. This is a bit tricky. But as rule of thumb, when code that you would've expect to work doesn't. Try to annotate your code with types, like shown below. You'll understand why this is so in time.

Here's the modified code:

main = do
  a <- askString "What is your name?"
  b <- askOther "How old are you?"

  putStrLn ""
  putStrLn "Name and age"
  putStrLn (a :: String)
  print (b :: Int)
  return ()

askString s = do
  putStrLn s
  getLine

askOther s = do
  putStrLn s
  readLn

Edit: Sorry, the code actually compiles now. Again, as your haskell matures, you'll see why askString and askOther does look different. Here is an example run:

$ runghc Hello.hs
What is your name?
Arash
How old are you?
22

Name and age
Arash
22

Problem

I was reading up on the deeper workings of the IO monad in Haskell on their wiki and I came across this code ``` main = do a <- ask "What is your name?" b <- ask "How old are you?" return () ask s = do putStr s readLn ``` Which makes sense to me. The ask function should print out the string given to it and return a line that can be passed into a or b. However loading this into GHCi I get problems. Tells me there isn't an instance of Read from use of ask and that I could import GHC.Read. That shouldn't be necessary. This code was on Haskell.org so I would think it should work. Was something in the language changed or is there some big piece of understanding that I am missing?

Original source