如何使用State Monad

时间:2019-05-23 09:26:30

标签: haskell state-monad

我已经问过一个有关了解单子状态的问题,但是现在我觉得这应该是另外一个了。

鉴于我实现了状态monad,我希望我的state是类似于Environment的数据结构:

环境

data Env=Env{
    envName::String,
    fileNames::[String]
}
instance Show Env where 
    show Env{envName=x,fileNames=xs} = "{ envName:"++x++
               " , files: ["++foldr (\t y-> t++","++y) "" xs ++"] }"

initEnv::IO Env
initEnv=do
    name<- getLine
    names<- getCurrentDirectory>>=listDirectory
    return Env{envName=name,fileNames=names}

我不知道如何将这种数据结构作为State集成到State monad中,以便能够更改环境的name,打印或使用它。似乎太宽泛了,但是如果没有完整的例子,我将无法理解:

州实施monad

newtype State s a = State {run::s->(a,s)} 

instance Functor (State s) where
    fmap=Control.Monad.liftM
instance Applicative (State s) where
    pure=return
    (<*>)=Control.Monad.ap
instance Monad (State s) where
    return a= State $ \k->(a,k) 
    (>>=) m f=State $ \s -> let (a,s')=run m s in
        run (f a) s'

我要实现的目标

readEnv::State a Env->Env
readEnv m =

changeEnvName::State a Env->State a Env
changeEnvName m =  --given the environment packed in a state , 
                   -- i want to change the name 

getEnvFileLengths::State a Env->[Int]
getEnvFileLengths s a= s>>= getLengths

getLengths::[String]->[Int]
getLengths xs=map length xs

PS 我知道我应该使用ReaderWriter monad,但我希望使用all in one方法来理解所有事物如何组合在一起。

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

如果正确获得类型签名,则可能会更容易取得进展:

readEnv::State Env Env
changeEnvName::String -> State Env ()
getEnvFileLengths::State Env [Int]

如果对您来说,这些类型看起来像是奇怪的类型选择,则可能值得尝试扩展newtype,然后查看它们是否显得更明智:

-- give me an initial environment from your store, I'll give you the new environment
-- to store and another copy of the environment as the result of the computation
readEnv :: Env -> (Env, Env)

-- give me a new name and the old environment, I'll give you a new environment and
-- a trivial acknowledgement that I'm done
changeEnvName :: String -> Env -> ((), Env)

-- give me an initial environment that you're storing, I'll give you the new
-- environment to store (actually same as the old one) and the result of the
-- length computations
getEnvFileLengths :: Env -> ([Int], Env)