[Haskell-cafe] newbie - IO issues (of course)

Bulat Ziganshin bulat.ziganshin at gmail.com
Sat Jun 24 02:08:14 EDT 2006

Hello Geoffrey,

Saturday, June 24, 2006, 8:38:31 AM, you wrote:

> getInt :: IO Int
> getInt = do
>             putStr "Enter number (zero to quit)"
>             line <- getLine
>             return (read line :: Int)

this procedure is fine, although there is specific function to read
data of any type, which is just equivalent to getLine+read. using it,
we can make routine even smaller:

getInt :: IO Int
getInt = do
            putStr "Enter number (zero to quit)"

> anIntList :: [Int]
> anIntList =
>         do
>             let n = getInt
>             if n == 0
>                 then return []
>                 else return (n : anIntList)

IO monad cannot escape, so you can't use inside non-IO function
(anIntList) an IO function (getInt)

this have very simple explanation - Haskell is pure language, that
meant that functions allways return the same results with same
arguments. your anIntList don't have arguments, so it should return
the same data on each call, really it's type signature meant that it
just a constant!

on the other side, return type "IO a" means that function can be
called in IO monad context (such as inside "main") and may return
different results even with the same arguments

as conclusion, anIntList should have type "IO [Int]". try to write it
yourself, i will help if you need it

ps: i definitely will write wiki "introduction to monads and i/o" next
week, it is so frequent source of beginner's troubles!

Best regards,
 Bulat                            mailto:Bulat.Ziganshin at gmail.com

More information about the Haskell-Cafe mailing list