DiffArray Performance

ketil+haskell at ii.uib.no ketil+haskell at ii.uib.no
Mon Nov 10 09:21:08 EST 2003


Glynn Clements <glynn.clements at virgin.net> writes:

> Stefan Reich wrote:

>> I'd like to ask a general question about unsafePerformIO: What exactly 
>> does unsafe mean? Just "impure" or rather "may lead to all kinds of 
>> problems, you better don't use this"?

> Essentially both. Haskell assumes purity (referential transparency),
> so impurity is likely to result in "all kinds of problems".

Here's a thing that can easily happen:

        my_trace = unsafePerformIO . putStrLn

        f x = trace "f called" `seq` ....

Now, when f is evaluated, it will print the message.  However, when f
is re-evaluated (normally with a different x), no message is printed!
Why?  Because the system will optimize by realizing that 'trace' is
called with the same argument, and it will just keep the old value
().  This behaviour depends on the level of optimization in your
compiler/interpreter, feel free to experiment!

The fix is of course to do

        my_trace ("f called with arg "++show x) `seq` ...

which will usually do what you expect.

Moral: unsafe means you can use it, but it doesn't give you any
complaining rights when it doesn't do what you think it should do.
(Sometimes in my darker moments, I feel we might bite the bullet, and
call the whole thing unsafeHaskell, and be done with it :-)

-kzm

PS: trace is defined in the libraries, not sure if it behaves more
reasonable in this respect.
-- 
If I haven't seen further, it is by standing in the footprints of giants


More information about the Glasgow-haskell-users mailing list