[Haskell-cafe] Using State monad with lens

William Yager will.yager at gmail.com
Sat Mar 21 15:43:26 UTC 2020


LambdaCase is useful for things like this.

On Sat, Mar 21, 2020 at 10:50 PM Henning Thielemann <
lemming at henning-thielemann.de> wrote:

>
> On Sat, 21 Mar 2020, Michael Hull wrote:
>
> > Hi,I use the State monad in a lot of places, but when I use it with the
> lens library, I find myself writing code
> > like:
> >
> > myFunc :: StateT MyState ([ResultType])
> > myFunc = do
> >    st <- get
> >    case st ^. some_property of
> >       True -> do
> >             my_value .= "Hello"
> >       True -> do
> >             my_value .= "Goodbye"
> >
> > I want to do something based on a 'state-variable', but I have to write
> 'get' -- is there a pattern that allows
> > me to avoid the intermediate 'st' variable?
>
> gets (^. some_property)
>
> But you still need a local variable for the result of 'gets'.
>
>
> > I want to write something like:
> >
> > myFunc = do
> >    case (get ^. some_property) of
> >       True -> do
> >             my_value .= "Hello"
> >       True -> do
> >             my_value .= "Goodbye"
> >
> > but that won't compile.
>
> There cannot be an according accessor, because getting the state needs
> access to the state in the monad. One could at least think of using
> LambdaCase._______________________________________________
> Haskell-Cafe mailing list
> To (un)subscribe, modify options or view archives go to:
> http://mail.haskell.org/cgi-bin/mailman/listinfo/haskell-cafe
> Only members subscribed via the mailman list are allowed to post.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.haskell.org/pipermail/haskell-cafe/attachments/20200321/c3ebaf5a/attachment.html>


More information about the Haskell-Cafe mailing list