Typescript Log - Implementing State Monad HaskellWiki Example

Posted on August 8, 2018

I’ve been learning about the State monad lately, and I’ve been looking for examples for which I can try out my new found knowledge. I usually do this by implementing it in another language, in this case Typescript. I found this example from the HaskellWiki site. As the comments say in the Haskell code, getNext will add 1 to the state, and return -1 to the state as the computed value. inc3 then advances the state three times.

With imperative programming and mutation this would be translated to declaring a variable with an initial value then incrementing that value by mutating that variable with the += operator.

The Haskell code above translates to Typescript like this. The nomenclature that the Javascript/Typescript FP communities have for the bind (>>=) operator is either chain, flatMap, or mergeMap. fp-ts chose chain.

I’m looking into using the StateT monad transformer in implementing UI states such as transitioning from one UI state to the next, and etc. Wish me luck!