简体   繁体   English

在Haskell中使用monad变压器RWST

[英]Working with monad transformer RWST in Haskell

I am using the monad transformer RWST in a Haskell project. 我在Haskell项目中使用了Monad变压器RWST。 Below is my source code: 下面是我的源代码:

type HSL a = RWST HBConfig [HBLog] a IO a       

runScript :: (HLanguage a, BuilderHSL a) 
          => HBConfig
          -> HSL a
          -> String
runScript hbConf srcHSL =  
    unsafePerformIO $ do
        (_, s, log) <- runRWST srcHSL hbConf initHLang
        return $ buildHSL hbConf s 

I implemented the function HSL HLangJS -> HLangJS as shown below: 我实现了HSL HLangJS -> HLangJS ,如下所示:

ujs :: HSL HLangJS -> HLangJS
ujs srcHSL =  
    unsafePerformIO $ do
        (a, s, log) <- runRWST srcHSL defaultHBConfig HLangJS
        return a 

Everything is working. 一切正常。 BUT!!! 但!!! I'm sure this is not the best solution! 我确定这不是最佳解决方案! The config and logs must be requested from transformer as shown in this code: 必须从转换器请求配置和日志,如以下代码所示:

ujs :: HSL a -> a
ujs rws = 
    unsafePerformIO $ liftIO $ do 
        c <- ask
        s <- get
        (a, _, _) <- runRWST rws c s
        return a

But this code is not working! 但是此代码不起作用! How can I implement this? 我该如何实施?

First of all, I think your HSL type may be more better. 首先,我认为您的HSL类型可能会更好。 HSL is monad but you've restricted it. HSL是monad,但您已对其进行了限制。 The state type and monad "value" type may be different. 状态类型和monad“值”类型可能不同。 Any time, you can restrict them. 您可以随时限制它们。

type HSL l a = RWST HBConfig [HBLog] l IO a

or better: 或更好:

type HSL l = RWST HBConfig [HBLog] l IO

Secondly, your HSL monad can have transformation HSL la -> l only with defaults values for config and initial state. 其次,您的HSL monad只能使用config和initial状态的默认值进行HSL la- HSL la -> l转换。 If you want hide this parameters, you should think about where you can get them? 如果要隐藏此参数,则应考虑从何处获取它们? For example, you can get it from IO: 例如,您可以从IO获取它:

ujs :: HSL l a -> IO l
ujs act = do
    config <- ...
    initState <- ...
    fst <$> execRWST act config initState

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM