Access to accounts in Monad Haskell State

I have it

newtype State' s a = State' { runState' :: (s, Counts) -> (a, s, Counts) }

      

Now I want to write a function

getCounts :: State' s a -> Counts

      

Is there a way to achieve this?

+3


source to share


1 answer


maybe this is what you are looking for:

getCounts :: State' s Counts
getCounts = State' (\ (s,c) -> (c,s,c))

      

you can use it inside calculation:

myStateComp = do
  -- whaever
  counts <- getCounts
  -- ...

      

and yes you can eval

too

Assuming yours evalState'

looks something like this:

evalState' :: State' s a -> s -> Counts -> a
evalState' st initState initCounts = 
    let (a,_,_) = runState st (initState,initCounts)
    in a

      

then you can get to the graphs like this:

evalState' getCounts initState initCount

      

Of course, this just gives you back initCount

- but without any calculations I can't see what else I could answer.

A real-world example might be something like this:



myComp = do
  -- ... do comp
  getCounts

      

and then

evalState' myComp initState initCount

      

will do any calculation inside and then return the last counter

alternative

alternative @bheklilr hinted at using

import Control.Monad.State

type State' s a = State (s, Counts) a

      

and

myStateComp = do
  -- whaever
  (state,counts) <- get
  -- ...

      

so your getCounts

here is really simplefmap snd get

+3


source







All Articles