State Monad Unlocked

State Monad:

An intentional Jargon for you!

Let’s do more.

Let’s generate an account number using a Generator class and ensure that the account number doesn’t exist by querying a repository. This example is taken from Functional and Reactive Modeling. But I loved this example and I hope it is ok to paste some code which I wrote based on the book explanation.

  • StateT is a monad transformer. It’s not important what it does here, except that the stateMonad function on StateT generates a State monad, with Generator as the state.
  • The import in the second line makes available the various combinators within the State monad as well as the generic Monad abstraction. (Remember, State is also a monad.)
  • modify is the combinator you used earlier that takes a function to modify the state. In our case, it’s creating another instance of Generator that will generate another account number.
  • gets applies the transformation function passed to it to the value and returns the updated State monad. So here it checks whether the generated account number already exists. As long as exists returns true, you need to execute the body of whileM_.
  • If you want to execute the computation and generate the next valid account number, you need to pass a start configuration of Generator and fire an exec on the monad.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Afsal Thaj

Afsal Thaj

A software engineer and a functional programming enthusiast at Simple-machines, Sydney, and a hardcore hiking fan.