Search code examples
haskellstate-monadfrege

Creating instance of State in Frege


In y-taka-23 adaptation of LYAH I found that most of snippets for Chapter 13 must deal with lack of State constructor, for example original Haskell code:

randomSt = State random 

is rewritten as:

randomSt = do
    gen <- State.get
    let (x, newGen) = random gen
    State.put newGen
    return x 

This of course has its own didactic merits! But I wonder if there is another way of creating instance of State. I know that this discrepancy between Frege and Haskell comes from the fact that State s a in Frege's Control.monad.State module is an abstract data type. Is it possible to define new concrete data type which derives from it and use its constructor instead?


Solution

  • Can't you just write a smart constructor?

    state :: (s -> (a, s)) -> State s a
    state f = do
        s <- State.get
        let (x, s') = f s
        State.put s'
        return x
    

    Write it once (maybe in a library you make available for download?) and then use it anywhere you need it.