What exactly is the difference between STRef and IORef and when do I use each of them? As far as I can tell they both are for mutable state so whats the point of both of them existing?
相关问题
- Understanding do notation for simple Reader monad:
- Making Custom Instances of PersistBackend
- Haskell: What is the differrence between `Num [a]
- applying a list to an entered function to check fo
- Haskell split a list into two by a pivot value
相关文章
- Is it possible to write pattern-matched functions
- Haskell underscore vs. explicit variable
- Top-level expression evaluation at compile time
- Stuck in the State Monad
- foldr vs foldr1 usage in Haskell
- List of checkboxes with digestive-functors
- How does this list comprehension over the inits of
- Replacing => in place of -> in function type signa
They each provide the same functionality, but for different monads. Use
IORef
if you need a managed ref inIO
, andSTRef
if you need one inST s
.EDIT: a brief example:
You can do more things in the
IO
monad than in theST
monad. The latter provides mutable references, the former provides mutable references, exception catching, threads, and of course IO.It is usually good Haskell practice to use the "weakest" or "more restricted" tool available that can solve your problem, because "weaker" tools tend to be easier to understand and analyze (another place this principle crops up in Haskell is in the
Applicative
versusMonad
distinction).So, if you only need mutable references, use
ST
. Future maintainers will be able to infer more about what your function does (and doesn't do) just by looking at the type.An example situation in which you are forced to use
IORef
s (or their cousinsMVar
s) is when having to share a mutable reference between two different execution threads.Also keep in mind that you can escape
ST
(which means you can runST
computations inside pure functions) but you can't escapeIO
.