When is it OK to use an IORef?

前端 未结 4 731
我寻月下人不归
我寻月下人不归 2021-01-30 12:27

One thing that has always confused me is whether or not it\'s an okay time to use an IORef. Are there any guidelines that should be followed when deciding whether or not to use

4条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-30 13:12

    Personally, I'd say it's fine to use IORefs when and only when you're already using IO. Otherwise, always State, unless you need the superior performance of ST. It's possible to use multiple threads of state with the State monad, with a few helper functions – you just make the state a tuple or record, and define functions to set, get, or update each field separately.

    In particular, there's not usually much point in using StateT s IO. If you're already in IO, you already have mutable state, so you might as well use it – ReaderT (IORef s) IO for example.

提交回复
热议问题