haskellimmutabilityio-monaddo-notationioref

How does readIORef work: creates copy or it does not?


What exactly does this code do? Is someMap a copy of the object (of ::Data.Map.Strict.Map) referred to by myMap or it's a reference only? I mean can someMap change (by another thread) after I read it with readIORef? Something like C's volatile... Is it possible? I expect that it's copy/snapshot, so any changes will not affect my someMap, or ...?

     do
        ....
        someMap <- readIORef myMap
        ....

Solution

  • readIORef :: IORef a -> IO a, so myMap must be IORef a and readIORef myMap :: IO a.

    And so someMap :: a, because it's to the left of <- in the do code line of the type IO a (it's a <- M a, always, in do notation).

    In your case, that a ~ Data.Map.Strict.Map k v, i.e. a pure immutable value.

    If another thread writes some new value into that myMap :: IORef (Data.Map.Strict.Map k v), then, it does. But it won't change the pure value that was already drawn from it before the switch-up.

    Effectful code has time. Pure referentially transparent code with immutable data is timeless.

    (What is true, is true, regardless of how long it takes to prove it.)