[Haskell-cafe] "Read-only" functions in State Monad

Twan van Laarhoven twanvl at gmail.com
Sat Jun 30 19:53:31 EDT 2007


Ken Takusagawa wrote:
> I'd like to have a state monad with the feature that I can somehow
> annotate using the type system that some functions are only going to
> read the state and not modify it.  Such read-only functions are only
> permitted to call other read-only functions, whereas state-modifying
> functions can call both read-only and other state-modifying functions.
> 
> How can I do this?  It does not seem to be straightforwardly doable
> with Control.Monad.State.

How about something like

 > readonly :: Reader a -> State a
 > readonly = gets . runReader

Implicit conversion is probably not possible with Control.Monad.State, 
you will have to make your own monad, maybe

 > newtype State2 w s a = State2 (State s a)
 > data Write

The phantom type w can be used to encode whether writing is needed 
(State2 Write) or not (forall w. State2 w)

 > get :: State2 w s s
 > put :: s -> State2 Write s s

Twan


More information about the Haskell-Cafe mailing list