st-monad

Modeling the ST monad in Agda

て烟熏妆下的殇ゞ 提交于 2019-12-03 06:06:58
This recent SO question prompted me to write an unsafe and pure emulation of the ST monad in Haskell, a slightly modified version of which you can see below: {-# LANGUAGE DeriveFunctor, GeneralizedNewtypeDeriving, RankNTypes #-} import Control.Monad.Trans.State import GHC.Prim (Any) import Unsafe.Coerce (unsafeCoerce) import Data.List newtype ST s a = ST (State ([Any], Int) a) deriving (Functor, Applicative, Monad) newtype STRef s a = STRef Int deriving Show newSTRef :: a -> ST s (STRef s a) newSTRef a = ST $ do (env, i) <- get put (unsafeCoerce a : env, i + 1) pure (STRef i) update :: [a] ->

How to put mutable Vector into State Monad

无人久伴 提交于 2019-12-03 03:14:16
I wrote small program in haskell to count all ocurences of Int values in Tree using State Monad with Vector: import Data.Vector import Control.Monad.State import Control.Monad.Identity data Tree a = Null | Node (Tree a) a (Tree a) deriving Show main :: IO () main = do print $ runTraverse (Node Null 5 Null) type MyMon a = StateT (Vector Int) Identity a runTraverse :: Tree Int -> ((),Vector Int) runTraverse t = runIdentity (runStateT (traverse t) (Data.Vector.replicate 7 0)) traverse :: Tree Int -> MyMon () traverse Null = return () traverse (Node l v r) = do s <- get put (s // [(v, (s ! v) + 1)