I\'m trying to understand the concept of monads and I want to know if this code is an implementation of this concept (in JavaScript).
I have function M which return new
This is a monoid pattern. Each state-updating operation, such as .setX(10)
, .addX(20)
, and so forth, is a computation that transforms one object. (To be syntactically valid, you would have to write it as a one-parameter function function(x) {x.addX(20);}
, but I think it's clearer if I use the short form.)
Two things make this a monoid. First, there is an identity element: .addX(0)
does nothing to its object. Second, any two operations can be combined. For example, .setX(10).addX(20)
is also a computation that transforms one object.
It is not a monad. The computations supported by your methods are limited to writing and updating this.x
. (.getX()
is not a member of the monoid because you can't chain anything after it). For example, with a monad you can have one member of a chain of operations execute an if-then-else to decide what comes next in the chain. Your methods can't do that.