Is this a monad?

前端 未结 2 985
既然无缘
既然无缘 2021-02-19 17:17

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

2条回答
  •  滥情空心
    2021-02-19 17:44

    Mutability aside; to my understanding, what you have written is closer to an applicative functor than either a monad, or a monoid.

    Again, to my understanding, a monoid is a Group (in the abstract algebraic sense) closed under a single operation mapping a single type unto itself. If you had only implemented add then you might say that your prototype chain implemented a monoid. But even then, you would have to specify the reduction yourself, by hand, as a binary operation, between each, and every argument, like so:

    M({x:0}).add(1).add(2)...add(100) === 1050; // or _.reduce([1..100],add)
    

    But since you have bound an indeterminate number of functions to a type (M), which all know how to 'unwrap' that type, apply the intended function, then restore the 'wrapper' on exit, then you have a sort of applicative functor.

    If you had found some way to compose the scopes of all functions operating on M, then you would be closer still to a monadic implementation:

    var bigOpFromLittleOps = 
           M({x:0})  .bind(function(x0){
    return Madd(1)   .bind(function(x1){
    return Madd(2)   .bind(function(x2){
    ...
    return Madd(100) .bind(function(x100){
    return Mreturn(x100);
    }); ... });});})() === 1050; // Overkill
    

    Such implementations are tricky, but give you the ability to slice and dice them into little pieces, and/or compose larger ones from smaller ones.

提交回复
热议问题