UP | HOME

A Really Trivial Monad

Generally some people saying that Monad is a computation that take a ’world’ as parameter and produce a result along with modified ’world’. And this a manner that doing impure in a pure language.

While thinking in terms of Parser, it means taking a String and produce a result along with the rest of the string which is not parsed1. Consequently, we think a monadic type in Haskell is just a function.

It probably is at most of time but not have to be. For instance the Maybe type. The trial mentioned below is a little similar with Maybe.

Actually I would to play with such idea:

To add a count of operations performed to it

Therefore the type is actually any value plus a count

  > newtype Sint a = Sint (a, Count)

In order to be a monad, it has to be a instance of Monad and the implementation of >>= is

  > p >>= f = let (a, c1) = getSint p
  >               (b, c2) = getSint (f a)
  >               in Sint (b, c1+c2)

It means keep the result of the second computation and combined the count together. Find full code here.

Now, I realize that to implement a Monadic Type, two key points we need to do, which also turn to be simple.

Footnotes: