Meaning of a newtype statement

216 views Asked by At

I have this statement:

newtype State st a = State (st -> (st, a))

Hence the type of State is:

State :: (st -> (st, a)) -> State st a

I cannot understand the meaning:

  • Are st and a just placeholder of two data-type? Right?
  • Does the statement means that State is a function that take as argument a function?
2

There are 2 answers

0
Chris Kuklewicz On BEST ANSWER

Yes and yes. The st is the state type and the a is the answer type.

0
Luis Casillas On

Yes. Data constructors are functions in Haskell, with the additional feature that you can pattern match against them. So, for example, if you have list of type fs : [st -> (st, a)] you can do map State fs :: [State st a].

The way the state monad works conventionally is that State st a represents a state transformer: a thing that takes an initial state, performs some computation that may depend or alter that state, and produces a result of type a. Composing two state transformers means creating a composite one that executes the first one with the initial state, and then executes the second one with the state that holds after the first one executes.

So the State monad implementation models that directly as a function of type st -> (st, a). Composing two such functions is just a matter of generating a composite function that feeds the initial state to the first one, passes the state that results from that to the second one, and returns the final state and result of the second one. In code:

bindState :: State st a -> (a -> State st b) -> State st b
bindState (State function1) f = 
    State $ \initialState -> let (nextState, firstResult) = function1 initialState
                             in f firstResult