Names

As I'm sure you may have guessed these flatMap'able things we've covered are in fact different kinds of monads. There are more common ones and you can make them up of any occasion. As different as the Async monad was to the container types other monads can be similarly different representing any sort of computation or structure. The important thing with monads and flatMap is that the provided function must return the same monad as the input. The type inside the monad can and often differs between the input and output. Another name for flatMap commonly used with monads is bind.

The name bind comes from how each flatMap takes a function which binds an input element as the function argument. In this example the names xs, ys, and zs each represent a monadic value not necessarily container types. Let's pretend unit is a 'magical' function that takes the normal value of the expression x * y * z and packages it into the nested monad types of xs, ys, and zs.

xs.flatMap(x ->
    ys.flatMap(y ->
        zs.flatMap(z -> {
            return unit(x * y * z);
        })
    )
).collect(Collectors.toList())

Look how that looks using the name bind and different indenting. It does seem to make sense as in for each instance of x in xs then the rest of the expression.

xs.bind(x ->
ys.bind(y ->
zs.bind(z -> {
  return unit(x * y * z);
}))).collect(Collectors.toList())

Rather than being called unit here, it would normally be called return as a function rather than a keyword in those languages and the expression is implicitly the return value so there no need for a keyword. In libraries of languages that already reserve the return keyword naming the function returns is sometimes done but then can lead to return returns(x).

Last updated

Was this helpful?