Polysemy: AtomicStateGautier DI FOLCO February 15, 2023 [Haskell] #haskell #polysemy #design #effects systems
One of the effect used over and over again in our previous example is
State, however, it's lack of atomicity can cause problems:
= forM_ ([0 .. 99] :: [Int]) $ \_ -> modify' @Int (+ 1) incThousand = void $ sequenceConcurrently $ map (const incHundred) ([0 .. 9] :: [Int]) incHundred
You might not get a
AtomicState is useful:
data AtomicState s m a where AtomicState :: (s -> (s, a)) -> AtomicState s m a AtomicGet :: AtomicState s m s
We can rewrite your code:
= forM_ ([0 .. 99] :: [Int]) $ \_ -> atomicModify' @Int (+ 1) incThousand' = void $ sequenceConcurrently $ map (const incHundred') ([0 .. 9] :: [Int]) incHundred'
Not a big change.
AtomicState provides interpreters that rely on atomic operations (
However, beware that other interpreters (such as
atomicStateToState) rely on
State and break the behavior.
See the full the code here.