-
New to I have a pattern I'm trying to implement where I have some mutable state in my effects (say, with the State effect), but with the ability to constrain my effects down to just a view of this state, where it can be read but not modified. In mtl world, I think this is relatively straightforward. If I have: With effectful, I'm not sure how to achieve the equivalent. I tried defining a custom Is there a better way to go about this? It's possible I'm thinking about this in a weird way or missing something obvious, so please also feel free to tell me if this is not a well-formed question :) |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 5 replies
-
If you do import Effectful
import Effectful.Dispatch.Dynamic
import Effectful.State.Static.Local
data View v :: Effect where
View :: View v m v
type instance DispatchOf (View v) = Dynamic
viewState :: State s :> es => Eff (View s : es) a -> Eff es a
viewState = interpret_ $ \View -> get then you can use View directly (as you said). Defining a MonadReader instance is possible with instance (View v :> es, MonadReader v (Eff es)) => MonadReader v (Eff es) where
ask = send View Note that it doesn't mention State. But it's a bad idea, since
See https://hackage.haskell.org/package/effectful-core-2.5.1.0/docs/Effectful-Dispatch-Dynamic.html#g:4 for more info. |
Beta Was this translation helpful? Give feedback.
-
That does exactly what I was trying to do. Thank you! I see that you wrote this as a dynamically dispatched effect. Just for my own understanding/learning - is it possible to write a statically dispatched version? And if so, what does that look like? I'm still trying to wrap my head around the difference, but I suppose I thought that if
What is? Defining a MonadReader? I did read the documentation, but I'm not sure I understand. Can you elaborate more here?
Ah, do you mean that if we had some other effect that needed to implement MonadReader, we couldn't do both that and this? If this is a bad idea - is there a "good" way to go about what I'm trying to do? Or would you consider it a fundamentally a bad abstraction? |
Beta Was this translation helpful? Give feedback.
If you do
then you can use View directly (as you said). Defining a MonadReader instance is possible with
Note that it doesn't mention State. But it's a bad idea, since