What is a good name for this state-like monad - haskell

This is something of a combination of State and Writer. I have checked the monad laws.
newtype M s a = M { runM :: s -> (s,a) }
instance (Monoid s) => Monad (M s) where
return = M . const . (mempty,)
m >>= f = M $ \s ->
let (s' ,x) = runM m s
(s'',y) = runM (f x) (s `mappend` s')
in (s' `mappend` s'', y)
StateWriter seems kinda lame.

"Introspective Writer"? It seems that the interesting you can do with it (that you can't do with Writer) is to write an introspect function that examines the state/output and changes it:
introspect :: (s -> s) -> M s ()
introspect f = M $ \s -> (f s, ())
I can't see that you can do this for writer, I think you'd have to make do with a post-transformer instead:
postW :: Writer w a -> (w -> w) -> Writer w a
postW ma f = Writer $ let (w,a) = getWriter ma in (f w,a)

Monoidal State. MonoState.MState. AccumState.

Maybe call SW (Statefull Writer), I think short names are rather intuitive and save some typing.

Related

Why is this Applicative instance for StateT working?

I am a Haskell (and CS) beginner. I am working my way through the haskellbook. I was implementing the Applicative instance for StateT where StateT is defined as :
newtype StateT s m a = StateT { runState :: s -> m (a, s) }
It is mentioned in the book that for creating an Applicative instance for StateT s m we need a Monad constraint on m rather than an Applicative constraint as one would expect. I had also reached the same conclusion on reading the accepted answer for the SO answer referenced in the book.
But, I tried to create an Applicative instance with an Applicative constraint on m for better understanding, and it successfully compiled. I also tried it on a few examples and it seems to work fine. Can someone please explain, what's wrong here?
instance (Applicative m) => Applicative (StateT s m) where
pure a = StateT $ \s -> pure $ (a, s)
(<*>) :: (StateT s m (a -> b)) -> (StateT s m a) -> (StateT s m b)
(StateT smf) <*> (StateT sma) = StateT $ \s -> (f) <$> (smf s) <*> (sma s)
where
f :: (a -> b, s) -> (a, s) -> (b, s)
f (ff, s) = \(a, s) -> (ff a,s)
*StateT> s1 = StateT (\s -> return (4, s))
*StateT> s2 = map (+) s1
*StateT> s3 = StateT (\s -> return (20, s))
*StateT> runState (s2 <*> s3) * 10
(24,10)
*StateT>
EDIT : As #Koterpillar advised me to try this with examples where state is also modified. I tried with this example. Also, here is the Monad constraint version, which I think also doesn't behave as it should. I think the problem is with states not being linked together somehow. If someone can shed some light on this topic, I would be grateful.
This is what <*> for StateT should do:
Run smf with the initial state
Run sma with the state from smf
Return this final state
This is what your code does:
Run smf with the initial state
Run sma with the initial state
Return this final state
In other words, the bug is that the state changes caused by smf are discarded.
We can demonstrate this issue with code that modifies the state in smf. For example:
s1 = StateT $ \s -> return (const (), s + 1)
s2 = StateT $ \s -> return ((), s)
Then runState (s1 <*> s2) 0 will return ((), 1) with the standard implementation, but ((), 0) with your one.

State Monad then (>>)

I would like to know the definition of >> for the Haskell state monad.
By my guess it pass one state to another:
(>>) :: State s a -> State s b -> State s b
State a >> State b = State $ \x -> b $ snd ( a x )
or
State a >> State b = State $ b . snd . a
Is this correct?
You're pretty much right. >> is actually more general than you suggest, but you can certainly use it with the type signature you indicate. If you're using State from its usual home, Control.Monad.Trans.State.Strict, or its home away from home, Control.Monad.State.Strict, State is actually just a type synonym:
type State s = StateT s Identity
where Identity is from Data.Functor.Identity and defined
newtype Identity x = Identity x
and StateT is defined
newtype StateT s m a = StateT {runStateT :: s -> m (a, s)}
So State s a is just a newtype wrapper around
s -> Identity (a, s)
This is essentially the same as the definition you imagine, but it allows State s to be compatible with the monad transformer StateT s, which is used to add state to arbitrary Monads.
instance Monad m => Monad (StateT s m) where
return a = StateT $ \s -> return (a, s)
StateT g >>= f = StateT $ \s -> g s >>= \(r,s') -> runStateT (f r) s'
So
StateT g >> StateT h = StateT $ \s -> g s >>= \(_,s') -> h s'
= StateT $ \s -> h $ snd $ runIdentity (g s)
= StateT $ h . snd . runIdentity . g
Irrelevant side note
The definition of StateT annoys me, because in my opinion it puts the elements of the pairs in the wrong order. Why wrong? Because mapping over (a, s) changes s while leaving a alone, and that is not what happens when mapping over a state transformer. End result: poor intuition.
I think this Wikipedia page gives a definition for (>>=) for the State monad:
m >>= f = \r -> let (x, s) = m r in (f x) s
Since (>>) is implemented in terms of (>>=) as follows:
m >> k = m >>= \_ -> k
one can derive the definition for (>>) for the state monad:
m >> k = \r -> let (x, s) = m r in ((\_ -> k) x) s
or when removing the noise:
m >> k = \r -> let (x, s) = m r in k s
Now since x does not play a part in the in clause, you can indeed use snd to get s, which can thus be rewritten to:
m >> k = \r -> k $ snd m r

Implementing Applicative (<*>) for StateT

This question has been asked before, but without a real answer. In fact the accepted answer suggests that it is not possible, despite the fact that
StateT is a Monad, and hence a superset of Applicative. As a result, the standard libraries simply use (<*>) = ap
(as Petr notes) composing applicatives always yields an applicative.
One of the implementations of MaybeT I've read about used
liftA2 (<*>) :: (Applicative f, Applicative f1) => f (f1 (a -> b)) -> f (f1 a) -> f (f1 b)
to implement Applicative but I can't make that work here. My work in progress has tried lots of options around the following:
-- (<*>) :: StateT s f (a -> b) -> State s f a -> State s f b
instance (Applicative f) => Applicative (StateT s f) where
pure a = StateT $ \s -> pure (a, s)
(StateT f) <*> (StateT g) = StateT $ \s -> -- f :: s -> m (a -> b, s), g :: s -> m (a, s)
let
mabs = f s -- mabs :: m (a -> b, s)
mab = fmap fst mabs
ms' = fmap snd mabs
in undefined
I'm wondering what I am missing, and hoping that I will learn something about Applicative in the process.
Tony uses some alternative notation, and Simon's answer is very terse, so here is what I ended up with:
-- (<*>) :: StateT s f (a -> b) -> State s f a -> State s f b
instance (Monad f, Applicative f) => Applicative (StateT s f) where
pure a = StateT $ \s -> pure (a, s)
StateT f <*> StateT a =
StateT $ \s ->
f s >>= \(g, t) -> -- (f s) :: m (a->b, s)
let mapper = \(z, u) -> (g z, u) -- :: (a, s) -> (b, s)
in fmap mapper (a t) -- (a t) :: m (a, s)
I had to declare f also a Monad, but that is OK as it is part of the definition of a Monad transformer, as I understand it.
An implementation (taken from Tony Morris' functional programming course) could be
(<*>) :: (Functor f, Monad f) =>
StateT s f (a -> b)
-> StateT s f a
-> StateT s f b
StateT f <*> StateT a =
StateT (\s -> (\(g, t) -> (\(z, u) -> (g z, u)) <$> a t) =<< f s)

Strict fmap using only Functor, not Monad

One irritation with lazy IO caught to my attention recently
import System.IO
import Control.Applicative
main = withFile "test.txt" ReadMode getLines >>= mapM_ putStrLn
where getLines h = lines <$> hGetContents h
Due to lazy IO, the above program prints nothing. So I imagined this could be solved with a strict version of fmap. And indeed, I did come up with just such a combinator:
forceM :: Monad m => m a -> m a
forceM m = do v <- m; return $! v
(<$!>) :: Monad m => (a -> b) -> m a -> m b
f <$!> m = liftM f (forceM m)
Replacing <$> with <$!> does indeed alleviate the problem. However, I am not satisfied. <$!> has a Monad constraint, which feels too tight; it's companion <$> requires only Functor.
Is there a way to write <$!> without the Monad constraint? If so, how? If not, why not? I've tried throwing strictness all over the place, to no avail (following code does not work as desired):
forceF :: Functor f => f a -> f a
forceF m = fmap (\x -> seq x x) $! m
(<$!>) :: Functor f => (a -> b) -> f a -> f b
f <$!> m = fmap (f $!) $! (forceF $! m)
I don't think it's possible, and also the monadic forceM doesn't work for all monads:
module Force where
import Control.Monad.State.Lazy
forceM :: Monad m => m a -> m a
forceM m = do v <- m; return $! v
(<$!>) :: Monad m => (a -> b) -> m a -> m b
f <$!> m = liftM f (forceM m)
test :: Int
test = evalState (const 1 <$!> undefined) True
And the evaluation:
Prelude Force> test
1
forceM needs a strict enough (>>=) to actually force the result of its argument. Functor doesn't even have a (>>=). I don't see how one could write an effective forceF. (That doesn't prove it's impossible, of course.)

Functor / Applicative instances for State in Haskell

After reading (and skimming some sections of) Wadler's paper on monads, I decided to work through the paper more closely, defining functor and applicative instances for each of the monads he describes. Using the type synonym
type M a = State -> (a, State)
type State = Int
Wadler uses to define the state monad, I have the following (using related names so I can define them with a newtype declaration later on).
fmap' :: (a -> b) -> M a -> M b
fmap' f m = \st -> let (a, s) = m st in (f a, s)
pure' :: a -> M a
pure' a = \st -> (a, st)
(<#>) :: M (a -> b) -> M a -> M b
sf <#> sv = \st -> let (f, st1) = sf st
(a, st2) = sv st1
in (f a, st2)
return' :: a -> M a
return' a = pure' a
bind :: M a -> (a -> M b) -> M b
m `bind` f = \st -> let (a, st1) = m st
(b, st2) = f a st1
in (b, st2)
When I switch to using a type constructor in a newtype declaration, e.g.,
newtype S a = S (State -> (a, State))
everything falls apart. Everything is just a slight modification, for instance,
instance Functor S where
fmap f (S m) = S (\st -> let (a, s) = m st in (f a, s))
instance Applicative S where
pure a = S (\st -> (a, st))
however nothing runs in GHC due to the fact that the lambda expression is hidden inside that type constructor. Now the only solution I see is to define a function:
isntThisAnnoying s (S m) = m s
in order to bind s to 'st' and actually return a value, e.g.,
fmap f m = S (\st -> let (a, s) = isntThisAnnoying st m in (f a, s))
Is there another way to do this that doesn't use these auxiliary functions?
If you look here, you will see that they define it this way:
newtype State s a = State { runState :: (s -> (a,s)) }
so as to give the inner lambda a name.
The usual way is to define newtype newtype S a = S {runState : State -> (a, State)}. Then instead of your isntThisAnnoying s (S m) you can write runState t s where t is the same as S m.
You have to use a newtype because type synonyms cannot be typeclass instances.

Resources