From what I understand, the three monadic laws are as follows (I come from a Java background instead of Haskell so pardon my syntax):
- Left Identity Law:
Monad.of(x).flatMap(y -> f(y)) = f(x)
- Right Identity Law:
- Associative Law:
I am also unable to find examples online. (I have found some people say Java Optional fails the Left Identity Law, but it uses null which is of any type and some may argue that it is not a proper value for Optional.) Is it possible if I could see some of such examples? Thanks in advance!
Edit 1: Recently, I took an exam and in the exam there was an instance of an example of an object that violates the Right Identity Law and satisfies the other two laws. Here it is:
class Counter { private final T val; private final int count; private Counter(T val, int count) { this.val = val; this.count = count; } public static Counter of(T val) { return new Counter(val, 1); } public Counter map(Function fn) { return new Counter(fn.apply(this.val), this.count + 1); } public Counter flatMap(Function fn) { Counter tmp = fn.apply(this.val); return new Counter(tmp.val, tmp.count); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof Counter)) { return false; } Counter ctx = (Counter) obj; return this.val.equals(ctx.val) && this.count == ctx.count; } }
Источник: https://stackoverflow.com/questions/746 ... ct-is-a-mo
Мобильная версия