Working with monad transformer RWST in Haskell

642 views Asked by At

I am using the monad transformer RWST in a Haskell project. 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:

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?

1

There are 1 answers

3
freestyle On BEST ANSWER

First of all, I think your HSL type may be more better. HSL is monad but you've restricted it. The state type and monad "value" type may be different. 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 l a -> l only with defaults values for config and initial state. If you want hide this parameters, you should think about where you can get them? For example, you can get it from IO:

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