[Haskell-cafe] Is it usual to read a Maybe (IORef a) ?

hs holgersiegel74 at yahoo.de
Wed Sep 3 14:51:20 EDT 2008


On Wednesday 03 September 2008 12:09:38 minh thu wrote:
> Hi,
>
> I'd like to write a data structure to be used inside the IO monad.
> The structure has some handles of type Maybe (IORef a),
> i.e. IORef are pointers and the Maybe is like null pointers.
>
> So I came up with the following functions :
>
> readHandle :: Maybe (IORef a) -> IO (Maybe a)
> readField :: (a -> b) -> Maybe (IORef a) -> IO (Maybe b)
>
> readHandle Nothing  = do
>   return Nothing
> readHandle (Just r) = do
>   v <- readIORef r
>   return $ Just v
>
> readField f h = do
>   m <- readHandle h
>   return $ fmap f m
>
> Is it something usual ?
> Are there any related functions in the standard libraries ?

A value of type Maybe (IORef a) is an optional pointer that must point to an 
object. If you want a pointer that points to either Nothing (aka null) or to a 
value, you should use IORef (Maybe a).

Then 

readHandle :: IORef (Maybe a) -> IO (Maybe a)
readHandle = readIORef

readfield :: (a -> b) -> IORef (Maybe a) -> IO (Maybe b)
readfield f p = (fmap . fmap) f (readIORef p)




More information about the Haskell-Cafe mailing list