[Haskell-cafe] Using unsafePerformIO safely
noteed at gmail.com
Thu Jun 25 03:02:49 EDT 2009
2009/6/25 Hector Guilarte <hectorg87 at gmail.com>:
> On Fri, Jun 26, 2009 at 12:58 AM, Brandon S. Allbery KF8NH
> <allbery at ece.cmu.edu> wrote:
>> On Jun 26, 2009, at 00:43 , Hector Guilarte wrote:
>> Thanks! Actually, if I understood well what you proposed, that's how I
>> first tought of doing it, but with a [Maybe String] and only append whenever
>> I actually had a (Just string), but as I said before, I don't think my
>> teacher is gonna like that solution since it is not going to print when the
>> interpreter finds the show instruction in the GCL code, it is gonna wait
>> until it finishes
>> I think maybe you don't quite have a grasp of lazy evaluation yet. Try
>> Also, nobody has told me why I shouldn't just use my original solution
>> using unsafePerformIO, is it really bad? is it dangerous? why is it
>> You were told earlier:
>>>>> Well, writing to the standard output is certainly a side effect. (This
>>>>> does not mean that you cannot use unsafePerformIO. The compiler,
>>>>> however, may assume that any value is free from side effects. This
>>>>> that you could get, in theory, less or more output from your program
>>>>> than you want. In this sense it is not "safe".)
>> Because pure (i.e. non-IO) values by definition never change, the compiler
>> is free to assume that it can do them exactly once and remember the result.
>> This means that it is possible for the compiler to evaluate your
>> unsafePerformIO once and never again... or, more likely, to notice that the
>> pure result is always () (because unsafePerformIO "hides" the IO from the
>> compiler) and optimize it away completely (the "do it exactly once" being at
>> compile time instead of run time).
> Ok, I got it this time, thanks! I should really talk this with my teacher.
> I'll post whatever he tells me... Let's hope he lets me just acumulate all
> the strings and print them in the end.
The notion you have about "print in the end" or (in a previous mail)
"print as soon as it is evaluated" is wrong.
Haskell is lazy.
This means things are evaluted when they are needed. Here, this means
the strings are produced *because* you print them out. If you don't
print them (or use them in another needed computation), they won't be
Also, garbage collection will reclaim the memory used by the strings
already evaluated and printed, so the "accumulation" doesn't really
occur from a memory usage point of view.
More information about the Haskell-Cafe