How to nondeterminate a value in a state?

In the following code, how can I replace put 1with some code that fits 1 or 2 non-deterministically?

import Control.Monad.List
import Control.Monad.Trans.State

test :: StateT Int [] Int
test = do
  put 1
  v <- get
  return v
+4
source share
2 answers

Your stack signature in the monad is already valid.

Pick up the calculations from the monad []and bind its value. This will cause a calculation:

test :: StateT Int [] Int
test = do
  s <- lift [1,2,3]
  put s
  v <- get
  return v

Testing to see it work:

*Main> runStateT test 10
[(1,1),(2,2),(3,3)]

Not only a lot of results, but the condition is also included in non-determinism.

If it testhad a type ListT (State Int) Int, only the results would be non-deterministic, the state would be divided between all branches in the calculation:

test :: ListT (State Int) Int
test = do
  s <- ListT $ return [1,2,3]
  put s
  v <- get
  return v

Result:

*Main> runState (runListT test) 10
([1,2,3],3)
+9

, - :

import Control.Monad.List
import Control.Monad.Trans.State
import System.Random (randomIO)

test :: StateT Int IO Int
test = do
  put1 <- liftIO $ randomIO
  put (if put1 then 1 else 2)
  v <- get
  return v

1 2

+2

All Articles