[Haskell-cafe] Is it usual to read a Maybe (IORef a) ?
wren ng thornton
wren at freegeek.org
Fri Sep 5 01:01:56 EDT 2008
minh thu wrote:
> 2008/9/4 Paul Johnson <paul at cogito.org.uk>:
>> I'd have thought you wanted "IORef (Maybe Thing)", which says that the
>> pointer always exists, but may not point to anything. On the other hand
>> "Maybe (IORef Thing)" says that the pointer may or may not exist.
> Yes, someone else said it too. But you saiy that regarding the pointer. If you
> look at the thing the pointer (if any) points at, what's the difference ?
> Either there is none : Nothing or IORef Nothing, or there is one :
> Just (IORef 5)
> or IORef (Just 5).
> The difference is you have to allocate a new IORef whenever you want to make
> the thing pointed at appear in the first case.
The difference is that IORef(Maybe a) lets someone in IO modify the
pointer in place. So if the IORef is pointing to Nothing, someone can
come and fix that so it's pointing to Just thing, without needing to
alter any of the data structure or context above the IORef. They can
also use this same ability to change an IORef pointing to something into
one pointing to Nothing, either for good or ill.
With Maybe(IORef a) the pointer either exists or does not, and that fact
can never be changed without rebuilding the datastructure/context above
the Maybe. Provided that the pointer exists, it can be freely modified
by anyone in IO to point to different things throughout its life (but
it's always pointing to something).
Depending on the exact semantics you're trying to model, either approach
can be correct. The way C and similar languages typically deal with
variables holding pointers is like IORef(Maybe a). A "const" pointer
---pointing to a fixed destination, where the memory at that destination
can be altered--- is similar to Maybe(IORef a).
Good luck with Data.IntMap, hopefully it'll simplify things.
More information about the Haskell-Cafe