Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Monads for Java programmers
- Imagine Optional and Stream had two additional methods each:
- ```java
- class Optional<T> {
- // the usual Optional stuff
- // ...
- public static <T> Optional<T> pure(T x) {
- return Optional.of(x);
- }
- public <U> Optional<U> bind(Function<T, Optional<U>> f) {
- return flatMap(f);
- }
- }
- ```
- ```java
- class Stream<T> {
- // ...
- public static <T> Stream<T> pure(T x) {
- return Stream.of(x);
- }
- public <U> Stream<U> bind(Function<T, Stream<U>> f) {
- return flatMap(f);
- }
- }
- ```
- Now try to imagine an interface X (with methods pure and bind), which could be implemented by both Optional and Stream.
- X = Monad
- Can't imagine this interface? Don't worry, it can't be expressed in Java.
- ## Conclusion
- In Java monad is a design pattern, while in Haskell it's a type class.
- ## Monad Laws (extracurricular)
- Every instance M of Monad must obey the following laws:
- ```java
- M.pure(a).bind(k) = k.apply(a)
- ```
- ```java
- m.bind(M::pure) = m
- ```
- ```java
- m.bind(x -> k.apply(x).bind(h)) = m.bind(k).bind(h)
- ```
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement