[Haskell-cafe] Functions with side-effects?

Creighton Hogg wchogg at login01.hep.wisc.edu
Wed Dec 21 08:49:42 EST 2005


On Wed, 21 Dec 2005, Daniel Carrera wrote:

> Thanks for all the help. I think things are much clearer now. And this bit:
> 
> > main = do putStrLn "Hello, what is your name?"
> >           name <- getLine
> >           putStrLn ("Hello, " ++ name ++ "!")
> 
> Looks quite straight forward.
> 
> I just wrote my very first IO program with Haskell:
> --//--
> main = do
>          x <- getLine
>          putStrLn( show(length x) )
> --//--
> 
> That's not so scary. The next thing I need to figure out is how to act 
> on the input data itself (not just its length). For example, if I wanted 
> a program to output the nth element of the fibonacci sequence:
> --//--
> $ ./fib 12
> 144
> --//--
> 
> My first inclination would be to write it as:
> --//--
> main = do
>          x <- getLine
>          putStrLn( show(fib x) )
> --//--
> 
> Of course that won't work because x is an IO String and 'fib' wants an 
> Int. To it looks like I need to do a conversion "IO a -> b" but from 
> what Cale said, that's not possible because it would defeat the 
> referential transparency of Haskell.

x is a String, getLine has type IO String.  That's what I 
was getting at in one of my last e-mails.
So you just need something that can read in a string and 
convert it to an int.
Something like
let y = (read x)
putStrLn $ show $ fib y
should work, yes?


More information about the Haskell-Cafe mailing list