[Haskell-cafe] Functions with side-effects?

Cale Gibbard cgibbard at gmail.com
Wed Dec 21 08:49:18 EST 2005


On 21/12/05, Daniel Carrera <daniel.carrera at zmsl.com> 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.

Actually, you're closer than you think here. x is actually of type String!
The problem is just that fib wants a number, so you need to read the string:
main = do x <- getLine
          putStrLn (show (fib (read x)))

There's a handy name for the composite (putStrLn . show) called
'print', so you can write:

main = do x <- getLine
          print (fib (read x)))

Cheers!
 - Cale


More information about the Haskell-Cafe mailing list