dosmath
dosmath

Reputation: 41

Accessing counts in State Monad haskell

I have this

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 any way I could achieve this?

Upvotes: 3

Views: 428

Answers (1)

Random Dev
Random Dev

Reputation: 52280

maybe this is what you are looking for:

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

you can then use it inside a computation:

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

and yes you can eval it too

assuming your evalState' is 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 Counts like this:

evalState' getCounts initState initCount

of course this just gives you back initCount - but without any more computation I don't see what else I could answer.

A real example might be something like this:

myComp = do
  -- ... do comp
  getCounts

and then

evalState' myComp initState initCount

will run any computation inside and then return the last count

alternative

the alternative @bheklilr was hinting at is 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 just fmap snd get

Upvotes: 3

Related Questions