How to put mutable Vector into State Monad

前端 未结 1 1117
时光说笑
时光说笑 2021-02-06 06:12

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         


        
相关标签:
1条回答
  • 2021-02-06 06:26

    When using ST state you're never explicitly passing the vector around (that's always in hidden in the s argument), but a reference to it. That reference is immutable and not copied, so you need not State but simply a reader to pass it implicitly.

    import Data.Vector
    import Control.Monad.Reader
    import qualified Data.Vector.Mutable as VM
    import Control.Monad.ST
    
    type MyMon3 s = ReaderT (VM.MVector s Int) (ST s)
    
    data Tree a = Null | Node (Tree a) a (Tree a) deriving Show
    main :: IO ()
    main = do 
        print $ runTraverse (Node Null 5 Null)
    
    runTraverse :: Tree Int -> Vector Int
    runTraverse t = runST $ do
            emp <- VM.replicate 7 0
            runReaderT (traverse t) emp
            Data.Vector.freeze emp
    
    traverse :: Tree Int -> MyMon3 s ()
    traverse Null = return ()
    traverse (Node l v r) = do
        d <- ask
        a <- lift $ VM.read d v
        lift $ VM.write d v (a + 1)
    
    0 讨论(0)
提交回复
热议问题