[Haskell-cafe] Using unsafePerformIO safely

Ketil Malde ketil at malde.org
Thu Jun 25 04:19:01 EDT 2009


Luke Palmer <lrpalmer at gmail.com> writes:

> mult2 x = unsafePerformIO $ do { print x; return (2*x) }

> main = do
>     let answer = mult2 21
>     print answer
>     print answer

> [this] would print 21,42,42.  Thus our *correct* transformation of programs
> changed behavior.

Just to expand a bit on this, if you now enable optimization, the
compiler might decide that mult2 is a small function and just inline
it, essentially turning the program back into the first version (which
I didn't quote).

So the output of your program also may depend on the compiler and
compiler switches you use - this too is frowned upon in the ivory
towers of functional programming. 

> Safe uses of unsafePerformIO are those where any such transformation won't
> change the overall behavior of the program.  They do exist

Debug.Trace.trace is, I guess, the most well-known example?  Which you might
even consider using here, since at least the library will try to
instruct the compiler not to inline, so it's somewhat less likely to
do unexpected things.

> The "list of strings" solution is *the* Haskell way to solve this problem.
> If your teacher does not accept the solution, then your teacher is not
> actually letting you program in Haskell.

...which would come as no big surprise.

I'm told that my old alma mater, the informatics department at the
University of Bergen, is now going to teach Haskell as a small part of
a small course titled "programming paradigms" or some such this fall.
Haskell FTW! (Or more like Haskell 1 - Java 9311, but still.)

-k
-- 
If I haven't seen further, it is by standing in the footprints of giants


More information about the Haskell-Cafe mailing list