Почему нам нужно проверять все три монадических закона при проверке того, является ли объект монадой?JAVA

Программисты JAVA общаются здесь
Ответить
Anonymous
 Почему нам нужно проверять все три монадических закона при проверке того, является ли объект монадой?

Сообщение Anonymous »


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:
monad.flatMap(y -> Monad.of(y)) = monad
  • Associative Law:
monad.flatMap(x -> f(x)).flatMap(x -> g(x)) = monad.flatMap(x -> f(x).flatMap(x -> g(x))) I have read that to show that an Object is a Monad, I will have to show that it satisfies all three monadic laws. This seems to imply that all three laws are necessary, and neither implies the other. However, I am having difficulty thinking of an examples where an Object can violate each one of the monadic laws without violating the other two.

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
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «JAVA»