[Haskell-cafe] closures with side effects

tpledger at ihug.co.nz tpledger at ihug.co.nz
Wed Jun 28 04:56:54 EDT 2006


dkarapet wrote:
> I have been trying to understand closures
> in haskell and how they relate
> to side effects. I have been looking
> around but all I find are trivial
> examples with no side effects. Please let
> me know if you know of any examples.

The side effects occur in the context that causes the
closure to be entered.

Here's a nigh-trivial example.

    myClosure :: IO ()
    myClosure = putStrLn "Hello, world."
    main      = myClosure >> myClosure

When myClosure is defined, the side effect doesn't occur
yet.  We just have a *definition* of an IO action that
hasn't yet been bound into the program's sequence of
actions.

When main binds myClosure into the program's sequence of
actions (twice), the side effect occurs (twice).  Depending
on the implementation of putStrLn, it may be faster the
second time because the same closure has been entered
before.

HTH,
Tom


More information about the Haskell-Cafe mailing list