Skip to content
Jerry Lan edited this page Nov 23, 2021 · 6 revisions

Monad

Definition: It is a statically typed language with generic support. And we can also treat this guy as a wrapper which takes given values then allows us to do some operations on them.

When analyzing Monad's source code, we can say "wow it is a class or trait".

Two important laws of Monad

The one is Identity Law and another is Associative Law.

Identity Law.(Examples are from Lazy)

As we all know, "Identity" means "same" or "no change". Thus, we can treat "of()" method as a fake-identity, because it behaves like identity.

static <T extends Comparable<T>> Lazy<T> of(Supplier<T> supplier) {
    return new Lazy<T>(Optional.ofNullable(supplier).orElseThrow());
}

Then we will use of method to discuss two different kinds of Identity Law: Left and Right

Left Identity Law

Definition: If we create a new monad and bind it to the function, the result should be the same as applying the function to the value. for instance:

Lazy.<T>of(x).flatMap(x -> f(x)).equals(f(x));

The instruction above should be true.

Right Identity Law

Definition: The result of binding a unit function to a monad should be the same as the creation of a new monad for instance:

lz.flatMap(x -> Lazy.<T>of(x)).equals(lz);

The instruction above should be true.

Associative Law

In mathematical definitions, associative law is this: b = f(a) c = g(b) thus c = g(f(a)) In computer science world, we can also apply this law. Assume we have this code:

Lazy.<T>of(14)
    .flatMap(x -> f(x))
    .flatMap(x -> g(x))
    .get();

We can put (x -> x + 1) in to the second function.

Lazy.<T>flatMap(x -> f(x).flatMap(y -> g(y)));

The instruction above is equal to code above(above) (if there are other things toward this part, please help to add, thanks)

Clone this wiki locally