[Haskell] Re: Initialisation without unsafePerformIO
ccshan at post.harvard.edu
Sun Jun 6 21:03:45 EDT 2004
On 2004-06-04T13:56:34-0400, Abraham Egnor wrote:
> I don't see how this technique can be at all safe:
> instance ReflectStorable s => Reflect (Stable s a) a where
> reflect = unsafePerformIO $
> do a <- deRefStablePtr p
> freeStablePtr p
> return (const a)
> where p = reflectStorable (undefined :: s p)
> reify :: a -> (forall s. Reflect s a => s -> w) -> w
> reify (a :: a) k = unsafePerformIO $
> do p <- newStablePtr a
> reifyStorable p (\(_ :: s p) -> k' (undefined :: Stable s a))
> where k' (s :: s) = (reflect :: s -> a) `seq` return (k s)
> The above means that a StablePtr will be allocated once per reify and
> destroyed once per reflect; I don't see how the code can guarantee
> that there will be only one reflect per reify. In fact, it seems
> quite likely that there will be far more reflects than reifys.
But (in a typical Haskell implementation) the action supplied as
an argument to unsafePerformIO is only performed once. The result
is memoized for future use. In particular, "reflect" only calls
"freeStablePtr" the first time it is invoked; thereafter it simply
produces the function "const a" that was computed the first time.
You can easily verify for yourself that "deRefStablePtr" is called
exactly once per "newStablePtr", regardless of whether the reified value
is looked up once, multiple times, or not at all. (The "not at all"
case is dealt with by the "seq".)
In any case, if you don't trust this explanation, then you can use
the preceding pieces of code in Section 4. The memory leak that this
code eliminates only exists for non-serializable data types, and
only significant if your program generates and discards many sets of
non-serializable parameters outside the IO monad over its lifetime.
Oleg + Ken
Edit this signature at http://www.digitas.harvard.edu/cgi-bin/ken/sig
I HATE SIGNATURES. AND I HATE MYSELF FOR USING THEM.
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Size: 189 bytes
Desc: Digital signature
Url : http://www.haskell.org//pipermail/haskell/attachments/20040606/486c1f23/attachment.bin
More information about the Haskell