[Haskell] Re: Initialisation without unsafePerformIO
Daan Leijen
daanleijen at xs4all.nl
Fri Jun 4 05:20:51 EDT 2004
On Fri, 04 Jun 2004 00:35:14 -0700, Ashley Yakeley <ashley at semantic.org> wrote:
> In article <20040601163515.GA8357 at momenergy.repetae.net>,
> John Meacham <john at repetae.net> wrote:
>
>> I am a fan of allowing top level declarations of the form:
>>
>> foo <- newIORef "foo"
>>
>> which would behave as an initializer, with the semantics being that it
>> be evaluated at most once before foos first use. (so it could be
>> implemented via unsafePerformIO or as an init section run before main).
>>
>> The
>> {-# NOINLINE foo #-}
>> foo = unsafePeformIO $ newIORef "foo"
>>
>> idiom is so common and useful, it should have some compiler support. It
>> is 'clean' too, since all we are doing is extending the "world" with new
>> state, but in a much cleaner/safer way then writing to a file or environment
>> variable or other methods of storing state in the world.
>
> Clean it is not:
>
> foo :: a
> foo <- newIORef undefined
>
> writeChar :: Int -> IO ()
> writeChar x = writeIORef foo x
>
> readString :: IO String
> readString = readIORef foo
>
> cast :: Char -> IO String
> cast c = (writeChar c) >> readString
If we check that the type of "foo" is monomorphic,
this is no longer unsafe.
-- Daan.
More information about the Haskell
mailing list