Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a good name for this state-like monad

Tags:

haskell

monads

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.

like image 567
luqui Avatar asked Dec 14 '10 05:12

luqui


People also ask

What is a state monad?

The state monad is a built in monad in Haskell that allows for chaining of a state variable (which may be arbitrarily complex) through a series of function calls, to simulate stateful code.

What is the reader monad?

The Reader monad (also called the Environment monad). Represents a computation, which can read values from a shared environment, pass values from function to function, and execute sub-computations in a modified environment. Using Reader monad for such computations is often clearer and easier than using the State monad.

Is a tuple a monad?

One thing I noticed was that Tuple does not have a Monad instance. Which already extremely heavily restricts what we can make the Monad instance be.

How does the IO monad work?

The I/O monad contains primitives which build composite actions, a process similar to joining statements in sequential order using `;' in other languages. Thus the monad serves as the glue which binds together the actions in a program.


2 Answers

"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)
like image 194
stephen tetley Avatar answered Oct 07 '22 22:10

stephen tetley


Monoidal State. MonoState.MState. AccumState.

like image 34
sclv Avatar answered Oct 07 '22 20:10

sclv