[Haskell-cafe] Using State monad with lens
Henning Thielemann
lemming at henning-thielemann.de
Sat Mar 21 14:49:08 UTC 2020
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.
More information about the Haskell-Cafe
mailing list