[Haskell-cafe] state monad transformer that adds or combines state

Vanessa McHale vanessa.mchale at iohk.io
Tue May 15 14:08:20 UTC 2018


You can simply use a state monad and then extract the data later when
you don't want the extra state, viz.

|

sum :: (Num a) => [a] -> a sum xs = flip execState 0 $ mapM_ (\x -> do {
s <- get ; put $ x + s }) xs

|


> For instance I often keep a pseudorandom generator as the state, and
use exception handling.

I'd use a monad transformer. Either `ExceptT` (which would add
exceptions to the state monad) or `StateT` (which would add state to an
exception monad).

On 05/15/2018 12:27 AM, Dennis Raddle wrote:
> I find myself using the state and exception monads at large scale in
> my programs. For instance I often keep a pseudorandom generator as the
> state, and use exception handling.
>
> In local computations, I may want to use some additional state. Is
> there a way to add a little extra state temporarily?
>
> Let's say I have
>
> data State1 = State1 StdGen
>
> type M1 = State State1
>
> data State2 = State2 State1 Int
>
> type M2 = State State2
>
> runM2 :: M2  a -> Int -> M1 a
>
> someFunc :: M1 Double
> someFunc = do
>   r <- <compute something pseudorandomly>
>   r2 <- runM2 (deeperFunc r) 3
>   <..etc..>
>
> deeperFunc :: Double -> M2 Double
>
>
>
> _______________________________________________
> Haskell-Cafe mailing list
> To (un)subscribe, modify options or view archives go to:
> http://mail.haskell.org/cgi-bin/mailman/listinfo/haskell-cafe
> Only members subscribed via the mailman list are allowed to post.

-- 



*Vanessa McHale*
Functional Compiler Engineer | Chicago, IL

Website: www.iohk.io <http://iohk.io>
Twitter: @vamchale
PGP Key ID: 4209B7B5

Input Output <http://iohk.io>

Twitter <https://twitter.com/InputOutputHK> Github
<https://github.com/input-output-hk> LinkedIn
<https://www.linkedin.com/company/input-output-global>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.haskell.org/pipermail/haskell-cafe/attachments/20180515/d719d924/attachment.html>
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 488 bytes
Desc: OpenPGP digital signature
URL: <http://mail.haskell.org/pipermail/haskell-cafe/attachments/20180515/d719d924/attachment.sig>


More information about the Haskell-Cafe mailing list