Advertisement
Guest User

Untitled

a guest
Mar 27th, 2017
51
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.07 KB | None | 0 0
  1. # Monads for Java programmers
  2.  
  3. Imagine Optional and Stream had two additional methods each:
  4.  
  5. ```java
  6. class Optional<T> {
  7. // the usual Optional stuff
  8. // ...
  9.  
  10. public static <T> Optional<T> pure(T x) {
  11. return Optional.of(x);
  12. }
  13.  
  14. public <U> Optional<U> bind(Function<T, Optional<U>> f) {
  15. return flatMap(f);
  16. }
  17. }
  18. ```
  19.  
  20. ```java
  21. class Stream<T> {
  22. // ...
  23.  
  24. public static <T> Stream<T> pure(T x) {
  25. return Stream.of(x);
  26. }
  27.  
  28. public <U> Stream<U> bind(Function<T, Stream<U>> f) {
  29. return flatMap(f);
  30. }
  31. }
  32. ```
  33.  
  34. Now try to imagine an interface X (with methods pure and bind), which could be implemented by both Optional and Stream.
  35.  
  36. X = Monad
  37.  
  38. Can't imagine this interface? Don't worry, it can't be expressed in Java.
  39.  
  40.  
  41. ## Conclusion
  42.  
  43. In Java monad is a design pattern, while in Haskell it's a type class.
  44.  
  45.  
  46. ## Monad Laws (extracurricular)
  47.  
  48. Every instance M of Monad must obey the following laws:
  49.  
  50. ```java
  51. M.pure(a).bind(k) = k.apply(a)
  52. ```
  53. ```java
  54. m.bind(M::pure) = m
  55. ```
  56. ```java
  57. m.bind(x -> k.apply(x).bind(h)) = m.bind(k).bind(h)
  58. ```
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement