"Read-only" functions in State Monad

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. --ken

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

Hi Ken,
2007/7/1, Ken Takusagawa
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.
I would suggest declaring a MonadReader instance for State, and writing your read-only functions as f :: MonadReader s m => Param -> m Result Would that solve your problem? Best, - Benja
participants (3)
-
Benja Fallenstein
-
Ken Takusagawa
-
Twan van Laarhoven