There was a question after reading this article: https://habrahabr.ru/company/cit/blog/262055/

Is the Builder pattern in Java an example of the Monad implementation?

Student s = new Student.Builder() .name("Vasya") .age(18) .language(Arrays.asList("chinese","english")) .build(); 

    1 answer 1

    In short, no.

    Let's see what is a monad? This is a data structure that has two pure and bind operations:

    pure(v) - getting monad for value v

    bind(f) - execution of the function f , which takes as its argument the value of the monad. returns a new monad.

    The following rules should be followed for this structure:

    1. Left indentality

      pure(v).bind(f) = pure(f(v)) applying the bind operation on a monad is equivalent to creating a monad from the value of the function f with argument v

    2. Right identity

      pure(v).bind(Monade::pure) = pure(v) applying the bind operation with the pure function to any monad is equivalent to the same monad.

    3. associativity

      pure(v).bind(f).bind(g) = pure(v).bind(g(f(v))) sequential use of bind operations with functions f and g on any monad is identical to using bind operations with the composition of these functions on this monad.

    Now, if you look at the builder pattern from the point of view of these rules, you will see that it does not have operations that satisfy these rules.

    • Java streams are not monads too? - TheSN
    • No, it's not. If the pure method is Stream.of and the bind method is Stream.map, all the rules are executed, except for the second one. because if you put another stream in the Stream.of method, it will return a stream of streams, which is not correct. - Artem Konovalov
    • Here are the real laws of monads, including Stream method names: 1) Stream.of(v).flatMap(f) ≡ f(v) , 2) stream.flatMap(Stream::of) ≡ stream , 3) stream.flatMap(f).flatMap(g) ≡ stream.flatMap(v -> f(v).flatMap(g)) and Stream does not contradict them - extrn