Monad

what is monad?

  • In functional programming, a monad is a design pattern that allows structuring even complex program logic in a way that is both generic and declarative.
  • A Monad is not a class or a trait; it is a concept.
  • Monads are structures that represent sequential computations in a context.
  • A Monad is an object that wraps another object.
  • In Monads, the output of a calculation at any step is the input to other calculations, which run as a parent to the current step.

monad in Java

a monad is a parameterised type such as Optional and Stream in Java which: 

Implements flatMap (a.k.a. bind) and unit (a.k.a. identity, return, Optional.of(), etc…).

Wraps computations in a particular context

https://gist.github.com/yc-zhang/1a78fe06e814b186f1571399b37a4005

Another useful ex

Let's think the result

https://gist.github.com/afcastano/e4182d344158cdbb6b65852bf67ef254#file-resultflatmap-java

Let's explain Stream#flatMap

        Stream.of("yuchen", "chenyu")
                .flatMap(s -> Stream.of("hello " + s))
                .forEach(System.out::println);

How we bind?

How we unit?

https://patternsinfp.wordpress.com/2010/12/31/stream-monad/

For us

use it to make code solid - isolate the side effects

make the code neat - describe the progress

focus method signature - just an instance method

use it everywhere - result\stream\future\business result

monad

By Yuchen Zhang

monad

  • 475