Simon Peyton Jones simonpj at
Fri Oct 11 15:08:22 UTC 2019

I'm deeply puzzled atomicModifyMutVar2#.  I have read the proposal<>, and the comments in primops.txt.pp (reproduced below).
Question 1
I think the "real" type of atomicModifyMutVar2 is

atomicModifyMutVar2# :: MutVar# s a

                     -> (a -> (a,b))

                     -> State# s

                     -> (# State# s, a, (a, b) #)
Nowhere is this explicitly stated, but I believe that the intended semantics of a call

case (atomicModifyMutVar2# mv f s) of (# s', x, r #) -> blah
Then, suppose the old value of the MutVar was 'old'

  *   The primop builds a thunk  t = f old
  *   The new value of the mutable variable is (fst t)
  *   The result r is t
  *   The result x is old
Question: is that correct?   We should state it explicitly.
Question 2
Next question: Why does f have to return a pair?  So far as I can tell, it's only so that a client can force it.   The 'b' part never seems to play a useful role.   So we could equally well have had

atomicModifyMutVar2# :: MutVar# s a

                     -> (a -> Box a)

                     -> State# s

                     -> (# State# s, a, Unit a #)
where Unit is defined in Data.Tuple

    data Unit a = Unit a
Now you can force the result of (f old), just as with a pair.  But the 'b' would no longer complicate matters.
Question: is the 'b' in the pair significant?   Or could we use Unit?
Question 3
In the comments below you say "but we don't know about pairs here".   Are you sure?  What stops you importing Data.Tuple into GHC.Prim?   This fancy footwork is one more complication, if it could be avoided.


primop  AtomicModifyMutVar2Op "atomicModifyMutVar2#" GenPrimOp

   MutVar# s a -> (a -> c) -> State# s -> (# State# s, a, c #)

   { Modify the contents of a {\tt MutVar\#}, returning the previous

     contents and the result of applying the given function to the

     previous contents. Note that this isn't strictly

     speaking the correct type for this function; it should really be

     {\tt MutVar\# s a -> (a -> (a,b)) -> State\# s -> (\# State\# s, a, (a, b) \#)},

     but we don't know about pairs here. }


   out_of_line = True

   has_side_effects = True

   can_fail         = True
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <>

More information about the ghc-devs mailing list