简体   繁体   中英

Out-of-date state using state monad

Here's a function runGame using the state monad:

runGame = do
    state <- get
    addPoints
    let newState = ...modify state in some way...
    put newState
  1. I get the state
  2. I modify it
  3. I put the new state.

Now suppose I modify the state in addPoints too:

addPoints = do
  modify (+1)

The problem is, the state I have in runGame is out of date now. So when I modify that state and put it back, I've nullified the changes from addPoints .

What's a good way to solve this? I dont want to re- get the state after every function call "just in case" that function modified the state. I can switch to always using modify instead of get and put but that makes my code awkward.

You're looking for atomic/transactional modifications to the state—that's pretty much exactly what modify provides. It's not possible to "slip" some state modifying operation between the get and the put with modify . If you don't use it you'll have to manage the complexity of ensuring that nothing happens between get and put .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM