Monad变压器:IO和状态 [英] Monad transformers: IO and state

查看:73
本文介绍了Monad变压器:IO和状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题很接近其他地方,但是我还没有找到任何专门解决这个问题的方法(至少不是以我能理解的方式).

This question is close to ground covered elsewhere, but I haven't found anything that addresses it specifically (at least not in a way that I'm able to understand).

我想根据各种随机选择来更新状态.由于我正在使用RandomSource类型类的实例,因此所有这些随机选择都位于IO monad中,如下所示:

I'd like to update state in a way that depends on various random choices. Because of the instance of the RandomSource typeclass that I'm using, all of these random choices live in the IO monad, as below:

main :: IO Int
main = do
         a <- pickRand [1..7]
         return a

         where pickRand lst = runRVar (choice lst) DevRandom

我想做的事情如下:存储一个[Int]类型的状态,如果随机选择的列表元素a大于3,则将其推入该状态.有小费吗?

What I'd like to do is something like the following: store a state of type [Int], and if the randomly chosen list element a is greater than 3 , push it onto the state. Any tips?

推荐答案

import Control.Monad
import Control.Monad.Trans.State
import Control.Monad.IO.Class
import Data.Random.RVar
import Data.Random.Source.DevRandom
import Data.Random.List

myFun :: StateT [Int] IO ()
myFun = do
  lst <- get
  r <- liftIO $ runRVar (randomElement lst) DevRandom
  put $ if r > 3 then (r:lst) else lst
  return ()


main :: IO ()
main = evalStateT myFun [1..10] >>= print

这篇关于Monad变压器:IO和状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆