DEV Community


Discussion on: Dependency injection and Reader Monad

gurghet profile image

What is the purpose of bind? How would you use it?

napicella profile image
Nicola Apicella Author

Hi Andrea!

Bind is used when you you have to deal with functions that cross between the normal world and the Monadic world.
For example say, you have a function which returns a monad:

var db = (name) => reader(() => name);
Enter fullscreen mode Exit fullscreen mode

The function returns a reader, so bind can be used to compose by unwrapping the value (i.e. to avoid getting a monad of a monad)

var getPersonName = reader((x) => x.toUpperCase());
var res = getPersonName.bind(db)"Andrea")
// returns "ANDREA"
Enter fullscreen mode Exit fullscreen mode

Does that make sense?

The concept can be found in any functional languages and not only, although the name may change. Another common name for bind is flatMap.
If you know Java you have probably used flatMap to avoid getting an optional of an Optional.