I'n looking at the State Monad's put and get:
ghci> :t get
get :: MonadState s m => m s
ghci> :t runState
runState :: State s a -> s -> (a, s)
ghci> runState get [1,2,3]
([1,2,3],[1,2,3])
In get's type signature: MonadState s m => m s, how does [1,2,3] have a type of MonadState s m? It's not clear to me what the types of s and m are.
Also, can you please say more as to how to use put?
ghci> :t put
put :: MonadState s m => s -> m ()
Overall, it seems that I don't understand what MonadState s m is. Could you please explain with put and get examples?
MonadState s m is a typeclass constraint, not a type. The signature:
get :: MonadState s m => m s
Says that for some monad m storing some state of type s, get is an action in m that returns a value of type s. This is pretty abstract, so let’s make it more concrete with the less-overloaded version of State from transformers:
get :: State s s
put :: s -> State s ()
Now say we want to use State to keep a simple counter. Let’s use execState instead of runState so we can just pay attention to the final value of the state. We can get the value of the counter:
> execState get 0
0
We can set the value of the counter using put:
> execState (put 1) 0
1
We can set the state multiple times:
> execState (do put 1; put 2) 0
2
And we can modify the state based on its current value:
> execState (do x <- get; put (x + 1)) 0
1
This combination of get and put is common enough to have its own name, modify:
> execState (do modify (+ 1)) 0
1
> execState (do modify (+ 2); modify (* 5)) 0
10
MonadState is the class of types that are monads with state. State is an instance of that class:
instance MonadState s (State s) where
get = Control.Monad.Trans.State.get
put = Control.Monad.Trans.State.put
So are StateT (the state monad transformer, which adds state to another monad) and various others. This overloading was introduced so that if you’re using a stack of monad transformers, you don’t need to explicitly lift operations between different transformers. If you’re not doing that, you can use the simpler operations from transformers.
Here’s another example of how to use State to encapsulate a map of variables with Data.Map:
import Control.Monad.Trans.State
import qualified Data.Map as M
action = do
modify (M.insert "x" 2) -- x = 2
modify (M.insert "y" 3) -- y = 3
x <- gets (M.! "x")
y <- gets (M.! "y")
modify (M.insert "z" (x + y)) -- z = x + y
modify (M.adjust (+ 2) "z") -- z += 2
gets (M.! "z") -- return z
main = do
let (result, vars) = execState action M.empty
putStr "Result: "
print result
putStr "Vars: "
print vars
In get's type signature: MonadState s m => m s, how does [1,2,3] have
a type of MonadState s m? It's not clear to me what the types of s and
m are.
ghci> runState get [1,2,3]
The function runState takes two arguments: the first is the State action to run, and the second is the initial state. So, since the initial state is [1,2,3] which is a list of integers (*), the state type s is just [Integer].
(*) Actually, [1,2,3] :: Num a => [a] before GHCi defaults it, but for simplicity's sake let's use [Integer] as GHCi does.
Hence, we see that runState is specialized to
runState :: State [Integer] a -> [Integer] -> (a, [Integer])
Now, about the first argument:
get :: MonadState s m => m s
We must have m s = State s a because we are passing it to runState which requires such type. Hence:
runState :: State [Integer] a -> [Integer] -> (a, [Integer])
get :: MonadState s m => m s
with m s = State [Integer] a
The latter equation can be simplified as follows:
runState :: State [Integer] a -> [Integer] -> (a, [Integer])
get :: MonadState s m => m s
with m = State [Integer]
and s = a
Substituting s:
runState :: State [Integer] a -> [Integer] -> (a, [Integer])
get :: MonadState a m => m a
with m = State [Integer]
Substituting m:
runState :: State [Integer] a -> [Integer] -> (a, [Integer])
get :: MonadState a (State [Integer]) => State [Integer] a
Now, the constraint MonadState a (State [Integer]) is satisfied only when a = [Integer]. This is tricky to see, since the MonasState type class exploits a functional dependency to enforce that every monad in that class has only one related state type. This is also made more complex from State being a wrapper around StateT. Anyway, we get:
runState :: State [Integer] a -> [Integer] -> (a, [Integer])
get :: MonadState a (State [Integer]) => State [Integer] a
with a = [Integer]
So,
runState :: State [Integer] [Integer] -> [Integer] -> ([Integer], [Integer])
get :: MonadState [Integer] (State [Integer]) => State [Integer] [Integer]
And since the constraint is satisfied:
runState :: State [Integer] [Integer] -> [Integer] -> ([Integer], [Integer])
get :: State [Integer] [Integer]
And now we can see the involved ground types.
Related
Say I have some Monadic type
data Example a = CheckIt {unwrap :: a}
instance Functor Example where
fmap f (CheckIt x) = CheckIt (f x)
instance Applicative Example where
pure = CheckIt
CheckIt f <*> CheckIt x = CheckIt (f x)
instance Monad (Example) where
return = CheckIt
e#(CheckIt a) >>= f = f a
and I have a function which returns an [a] based on some input:
fetchList :: b -> [Int]
fetchList _ = [1,2,3,4]
and a function that returns an IO [a] (simplified from real implementation):
basicIoWrap :: [a] -> IO [a]
basicIoWrap x = return x
and I wish to run this IO and then extract an Example [a] from it:
The following does not work:
foo :: b -> Example [a]
foo val = (basicIoWrap (fetchList val)) >>= \list -> return list
complaining about different monad types
Couldn't match type ‘IO’ with ‘Example’
Expected type: Example [a]
Actual type: IO [Int]
So I understand that this is exactly the usecase for Monad transformers, but I am really struggling figuring out how to apply them in context. Say I had a transformer:
newtype ExampleT m a = ExampleT {runExampleT :: m (Example a)}
and I rephrased my signature to
foo :: b -> ExampleT (IO [a])
I am unclear what the function body would then look like, and also, how I would eventually extract an Example [a] from this? Wouldn't runExampleT ExampleT (IO [a]) give an IO [Example a], thus simply punting the multi Monad problem further down the road?
You can never safely "escape" from IO, but if you have a value of a type like Example (IO [a]) and Example is at least a Traversable, then you can turn it into IO (Example [a]) with the sequence function. Using this method you could write your foo function as:
foo :: b -> IO (Example [a])
foo = sequence . return . basicIoWrap . fetchList
Since you must already be working in the IO monad in order to use basicIoWrap, you can access the Example [a]. For example:
do input <- getLine
(Example as) <- foo input
mapM_ print as
In the following example:
toss :: Double -> RVar Bool
toss p = do
q <- uniform 0 1
return $ q <= p
toss' :: MonadRandom m => Double -> m Bool
toss' p = runRVar (toss p) StdRandom
foo :: StateT Int RVar ()
foo = do
h <- lift $ toss' 0.5
if h then put 100 else put 0
bar :: StateT Int RVar ()
bar = do
h <- lift $ toss 0.5
if h then put 404 else put 200
testFoo :: MonadRandom m => m ((), Int)
testFoo = runRVar (runStateT foo 0) StdRandom
testBar :: MonadRandom m => m ((), Int)
testBar = runRVar (runStateT bar 0) StdRandom
I am confused about:
why the signature of foo is forced to be StateT Int RVar () even though toss' has signature m Bool for some MonadRandom m
Why testFoo has to be run with some StdRandom even though toss' already runRVar with StdRandom. It makes sense from a type perspective, but which StdRandom end up being used? If this question makes any sense at all.
Would it be possible to rewrite foo's signature as MonadRandom m => StateT Int m ()
When monomorphism restriction is on (it's on by default), all types of top-level binders will be inferred monomorphic.
You should add RVar to the monad stack like you did in bar. MonadRandom is too general.
StdRandom is just a data constructor, so it has no specific state. random-fu should handle updating state automatically.
Just add the signature. See 1.
If we have the following two functions, add and subtract, it is simple to chain them to run a series of calculations on an input:
add :: Int -> State Int ()
add n = state $ \x -> ((),x+n)
subtract :: Int -> State Int ()
subtract n = state $ \x -> ((),x-n)
manyOperations :: State Int ()
manyOperations = do
add 2
subtract 3
add 5
--etc
result = execState manyOperations 5
--result is 9
If we want to print out the state after each calculation is done, we use the StateT monad transformer:
add :: Int -> StateT Int IO ()
add n = StateT $ \x -> print (x+n) >> return ((),x+n)
subtract :: Int -> StateT Int IO ()
subtract n = StateT $ \x -> print (x-n) >> return ((),x-n)
manyOperations :: StateT Int IO ()
manyOperations = do
add 2
subtract 3
add 5
main = runStateT manyOperations 5
-- prints 7, then 4, then 9
Is it possible to replicate this "combined computation and printing" without StateT or any custom datatypes?
As far as I know it's possible to do all the processes that MaybeT IO a can do using IO (Maybe a), but it seems like that's because it's just nested monads. On the other hand, StateT might not have an alternative because s -> (a,s) is fundamentally different to s -> m (a,s)
I can only see two directions the code could go: using State Int (IO ()) or IO (State Int ()), but both of these seem nonsensical given the implementation of StateT
I believe it is impossible. Am I correct?
Note: I know this is completely impractical, but I couldn't find any solution after some hours of work, which means I'm correct or my skills aren't enough for the task.
Of course you can do all the plumbing yourself. Monads don't add anything new to Haskell, they just enable a ton of code reuse and boilerplate reduction. So anything you can do with a monad, you can laborously do by hand.
manyOperations :: Int -> IO ()
manyOperations n0 = do
let n1 = n0 + 2
print n1
let n2 = n1 - 3
print n2
let n3 = n2 + 5
print n3
If the amount of repetition in the above function is too much for you (it is for me!) you could try to reduce it with a 'combined computation and printing' function but at this point you're bending over backwards to avoid StateT.
-- a bad function, never write something like this!
printAndCompute :: a -> (a -> b) -> IO b
printAndCompute a f = let b = f a in print b >> return b
-- seriously, don't do this!
manyOperations n0 = do
n1 <- printAndCompute (+2) n0
n2 <- printAndCompute (-3) n1
n3 <- printAndCompute (+5) n2
return ()
I'm not sure if this is quite what you're looking for, but you could define an operation which takes a stateful operation that you alread have, and prints out the state after performing the operation -
withPrint :: (Show s) => State s a -> StateT s IO a
withPrint operation = do
s <- get
let (a, t) = runState operation s
liftIO (print t)
put t
return a
and then do
manyOperations :: StateT Int IO ()
manyOperations = do
withPrint (add 2)
withPrint (subtract 3)
withPrint (add 5)
-- etc
This doesn't avoid using StateT but it abstracts out the conversion of your regular, non-IO state operations into IO-ful state operations so you don't have to worry about the details (aside from adding withPrint when you want the state to be printed.
If you don't want the state printed for a particular operation, you could define
withoutPrint :: State s a -> StateT s IO a
withoutPrint operation = do
s <- get
let (a, t) = runState operation s
put t
return a
which is actually equivalent to
import Control.Monad.Morph
withoutPrint :: State s a -> StateT s IO a
withoutPrint = hoist (\(Identity a) -> return a)
using hoist from Control.Monad.Morph to transform the monad underlying StateT from Identity to IO.
You can completely avoid those data types by using s -> IO (a, s) directly, substituting for a and s appropriately. It definitely won't be as nice though.
It would look something like this:
-- This makes StateIO s act as a shorthand for s -> IO (a, s)
type StateIO s a = s -> IO (a, s)
add :: Int -> StateIO Int ()
add n = \x -> print (x+n) >> return ((),x+n)
sub :: Int -> StateIO Int ()
sub n = \x -> print (x-n) >> return ((),x-n)
manyOperations :: StateIO Int ()
manyOperations = -- Using the definition of (>>=) for StateT
\s1 -> do -- and removing a lambda that is immediately applied
(a, s2) <- add 2 s1
(a, s3) <- sub 3 s2
add 5 s3
result :: IO ((), Int)
result = manyOperations 5
The state has to be explicitly threaded through all the operations. This is a major gain we get from using the StateT datatype: the (>>=) method of its Monad instance does all this for us! We can see from this example, though, that there is nothing magical going on in StateT. It's just a very nice way of abstracting out the threading of state.
Also, the relationship between StateT and State is the opposite of the relationship between MaybeT and Maybe: State is defined in terms of StateT. We can see that fact expressed in this type synonym:
type State s = StateT s Identity
It is a transformer over the Identity type (which has the trivial Monad instance).
I'm twisting my brain into knots trying to understand how to combine the State monad with Maybe.
Let's start with a concrete (and intentionally trivial/unnecessary) example in which we use a State monad to find the sum of a list of numbers:
import Control.Monad.State
list :: [Int]
list = [1,4,5,6,7,0,3,2,1]
adder :: Int
adder = evalState addState list
addState :: State [Int] Int
addState = do
ms <- get
case ms of
[] -> return 0
(x:xs) -> put xs >> fmap (+x) addState
Cool.
Now let's modify it so that it returns a Nothing if the list contains the number 0. In other words, evalState addState' list should return Nothing (since list contains a 0). I thought it might look something like this...
addState' :: State [Int] (Maybe Int)
addState' = do
ms <- get
case ms of
[] -> return (Just 0)
(0:xs) -> return Nothing
(x:xs) -> put xs >> fmap (fmap (+x)) addState'
...it works but I assume there's a better way to do this...
I've played around with StateT and MaybeT and I can't get them to work. I've looked at a couple of intros to Monad transformers but they either didn't touch on this particular combo (i.e., State + Maybe) or the examples were too complex for me to understand.
TL;DR: I'd appreciate if someone could show how to write this (admittedly trivial) piece of code using StateT and MaybeT (two examples). (I'm assuming it isn't possible to write this code without the use of transformers - is that incorrect?)
P.S. My understanding is that StateT is probably better suited for this example, but it would be helpful conceptually to see both examples, if not too much trouble.
Update: As pointed out by #Brenton Alker, my first version of the code above doesn't work because of simple typo (I was missing an apostrophe). In the interest of focusing the question on the use of StateT/MaybeT, I'm correcting the post above. Just wanted to include this note to give context to his post.
The type I would recommend using is:
StateT [Int] Maybe Int
A really simple way to use Maybe/MaybeT is to just call mzero whenever you want to fail and mplus whenever you want to recover from a failed computation. This works even if they are layered within other monad transformers.
Here's an example:
addState' :: StateT [Int] Maybe Int
addState' = do
ms <- get
case ms of
[] -> return 0
(0:xs) -> mzero
(x:xs) -> put xs >> fmap (fmap (+x)) addState
-- This requires generalizing the type of `addState` to:
addState :: Monad m => StateT [Int] m Int
Notice that I wrote that in such a way that I didn't use any Maybe-specific operations. In fact, if you let the compiler infer the type signature it will deduce this more general type instead:
addState' :: MonadPlus m => StateT [Int] m Int
This works because StateT has the following MonadPlus instance:
instance MonadPlus m => MonadPlus (StateT s m) where ...
And Maybe will type-check as an instance of MonadPlus, which is why the above code works when we specialize m to Maybe.
I believe your solution is basically correct, you just have a few minor issues.
Your recursive call to addState is missing the prime - ie. it should be addState' (I suspect this is just an issue in pasting the question, given the reported error)
You're asserting adder :: Int, but in the new version it should be adder :: Maybe Int - I think this is the type error you're getting.
Unfortunately, I don't have the resources to try a transformers version at the moment.
This example implements a simple Stack using MaybeT (State [Int]) Int.
We have a State Monad that holds s -> (a, s) being s :: [Int] (a Stack) and a :: Maybe Int (Just the element you get out/put into the Stack or Nothing when you try to pop something out of an empty stack).
-- -----------------------------------------
-- -----------------------------------------
import Control.Monad.Trans.State
import Control.Monad.Trans.Maybe
-- -----------------------------------------
-- -----------------------------------------
pop2 :: MaybeT (State [Int]) Int
pop2 = MaybeT . state $ \xx -> case xx of
[] -> (Nothing, [])
x:xs -> (Just x, xs)
push2 :: Int -> MaybeT (State [Int]) Int
push2 x = MaybeT . state $ \xs -> (Just x, x:xs)
-- -----------------------------------------
-- -----------------------------------------
dup2 = do
x <- pop2
push2 x
push2 x
-- -----------------------------------------
-- -----------------------------------------
main = do
print $ runState (runMaybeT dup2) [12, 34, 56]
print $ runState (runMaybeT dup2) []
When we run the program, we get:
(Just 12,[12,12,34,56])
(Nothing,[])
Let's review the types:
Originally,
MaybeT :: m (Maybe a) -> MaybeT m a (m a monad enclosing a Maybe a)
We use m == State [Int] and a == Int
Therefore
MaybeT :: (State [Int]) (Maybe Int) -> MaybeT (State [Int]) Int
and
runMaybeT :: MaybeT m a -> m (Maybe a) == MaybeT (State [Int]) Int -> (State [Int]) (Maybe Int) (runMaybeT pulls out what MaybeT encloses).
and
runState of (State [Int]) (Maybe Int) == [Int] -> ((Maybe Int), [Int])
(runState pulls out what (State [Int]) (Maybe Int) encloses).
I find it difficult for me to understand the MonadState .
The reason maybe most of the examples mixing up with record syntax in their data structure.
So, I tried to implement the MonadState without using record syntax.
The following code I wrote did pass the compiler, but it seems totally nonsense to me.
What is wrong with these code?
Is there a simple example of implementing MonadState without using record syntax?
data Foo a b = Foo (Maybe ([a],b)) deriving (Show)
unwrapFoo :: Foo a b -> Maybe ([a],b)
unwrapFoo (Foo x) = x
instance Monad (Foo [a]) where
return x = Foo $ Just ([], x)
m >>= f = case unwrapFoo m of
Just (_, r) -> f r
Nothing -> Foo Nothing
instance MonadState Int (Foo [a]) where
get = Foo $ Just ([], 1)
put _ = Foo $ Just ([],())
*Main> get :: Foo [a] Int
Foo (Just ([],1))
*Main> put 3 :: Foo [a] ()
Foo (Just ([],()))
*Main>
So let's start with the basic idea of the State Monad.
newtype MyState s a = MyState (s {- current state -}
-> (s {- New state -}, a {- New value -}))
unwrap (MyState f) = f
So now we need to implement >>= and return.
return is pretty easy:
return a = MyState $ \s -> -- Get the new state
(s, a) -- and pack it into our value
In other words, this just passes the current state through with a new value.
And now >>=
(MyState f) >>= g = MyState $ \state ->
let (newState, val) = f state
MyState newF = g val
in newF state
So we get a new state, feed it into our existing state monad, then pass the resulting value/state pair into g and return the result of that.
The total number of differences between this and the record syntax is just that I had to manually define unwrap.
To complete our monad
runState = unwrap
get = MyState \s -> (s, s)
put a = MyState \s -> (a, ())