Idris2/libs/base/Control/Monad/ST.idr
Edwin Brady ad632d825d Remove linearity subtyping
It's disappointing to have to do this, but I think necessary because
various issue reports have shown it to be unsound (at least as far as
inference goes) and, at the very least, confusing. This patch brings us
back to the basic rules of QTT.

On the one hand, this makes the 1 multiplicity less useful, because it
means we can't flag arguments as being used exactly once which would be
useful for optimisation purposes as well as precision in the type. On
the other hand, it removes some complexity (and a hack) from
unification, and has the advantage of being correct! Also, I still
consider the 1 multiplicity an experiment.

We can still do interesting things like protocol state tracking, which
is my primary motivation at least.

Ideally, if the 1 multiplicity is going to be more generall useful,
we'll need some kind of way of doing multiplicity polymorphism in the
future. I don't think subtyping is the way (I've pretty much always come
to regret adding some form of subtyping).

Fixes #73 (and maybe some others).
2020-12-27 19:58:35 +00:00

57 lines
1.1 KiB
Idris

module Control.Monad.ST
import Data.IORef
export
data STRef : Type -> Type -> Type where
MkSTRef : IORef a -> STRef s a
export
data ST : Type -> Type -> Type where
MkST : IO a -> ST s a
export
runST : (forall s . ST s a) -> a
runST p
= let MkST prog = p {s = ()} in -- anything will do :)
unsafePerformIO prog
mutual
export
Functor (ST s) where
map fn st = pure $ fn !st
export
Applicative (ST s) where
pure x = MkST (pure x)
(<*>) f a = pure $ !f !a
export
Monad (ST s) where
MkST p >>= k
= MkST $ do p' <- p
let MkST kp = k p'
kp
export
newSTRef : a -> ST s (STRef s a)
newSTRef val
= MkST $ do r <- newIORef val
pure (MkSTRef r)
%inline
export
readSTRef : STRef s a -> ST s a
readSTRef (MkSTRef r) = MkST $ readIORef r
%inline
export
writeSTRef : STRef s a -> (val : a) -> ST s ()
writeSTRef (MkSTRef r) val = MkST $ writeIORef r val
export
modifySTRef : STRef s a -> (a -> a) -> ST s ()
modifySTRef ref f
= do val <- readSTRef ref
writeSTRef ref (f val)