[Haskell-cafe] What are side effects in Haskell?

Peter Verswyvelen bugfact at gmail.com
Fri Dec 26 09:38:35 EST 2008


Using GHCi I found it informative to see that  IO indeed is a kind of state
monad. Here's a GHCi session to show that:
Prelude> :m GHC.Prim
Prelude GHC.Prim> :i IO
newtype IO a
  = GHC.IOBase.IO (State# RealWorld -> (# State# RealWorld, a #))
        -- Defined in GHC.IOBase
instance Monad IO -- Defined in GHC.IOBase
instance Functor IO -- Defined in GHC.IOBase

So every "IO a" action takes the RealWorld as input, and outputs
the RealWorld and some extra value "a" :)

2008/12/23 Adrian Neumann <aneumann at inf.fu-berlin.de>

> Am 23.12.2008 um 15:16 schrieb Hans van Thiel:
>
>  Hello All,
>>
>> I just saw somewhere that one of the purposes of monads is to capture
>> side effects. I understand what a side effect is in C, for example. Say
>> you want to switch the contents of two variables. Then you need a third
>> temporary variable to store an intermediate result. If this is global,
>> then it will be changed by the operation.
>>
>
> But the two variables have also changed. After all they have different
> values after the switch. You see, even locally changing a variable is a
> side-effect. It changes the state of the program. Pure Haskell programs on
> the other hand have no notion of state, there are no variables which can
> change their value. Every time you want to manipulate something you're
> actually generating an new copy. You mustn't think of a haskell program as a
> series of changes to some state.
>
> However when you *do* want state you can simulate it with a monad. The IO
> Monad is a special case here, since its actions don't change your program,
> they change the "world" the program is running in (writing files etc.).
> getLine etc are functions when you think of them as taking a hidden
> parameter, the state of the world. So getChar would become
>
> getChar :: World -> (Char,World)
>
> but the world stays hidden inside the IO Monad.
>
> Regards,
>
> Adrian
>
>
> _______________________________________________
> Haskell-Cafe mailing list
> Haskell-Cafe at haskell.org
> http://www.haskell.org/mailman/listinfo/haskell-cafe
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20081226/ef37bce0/attachment.htm


More information about the Haskell-Cafe mailing list