"Read-only" functions in State Monad

Previous Topic Next Topic
 
classic Classic list List threaded Threaded
3 messages Options
Reply | Threaded
Open this post in threaded view
|

"Read-only" functions in State Monad

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.  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
_______________________________________________
Haskell-Cafe mailing list
[hidden email]
http://www.haskell.org/mailman/listinfo/haskell-cafe
Reply | Threaded
Open this post in threaded view
|

Re: "Read-only" functions in State Monad

Twan van Laarhoven
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
_______________________________________________
Haskell-Cafe mailing list
[hidden email]
http://www.haskell.org/mailman/listinfo/haskell-cafe
Reply | Threaded
Open this post in threaded view
|

Re: "Read-only" functions in State Monad

Benja Fallenstein
In reply to this post by Ken Takusagawa
Hi Ken,

2007/7/1, Ken Takusagawa <[hidden email]>:
> 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
_______________________________________________
Haskell-Cafe mailing list
[hidden email]
http://www.haskell.org/mailman/listinfo/haskell-cafe