DEV Community

Discussion on: What dev topic do you think you should understand, but don't?

Collapse
 
kspeakman profile image
Kasey Speakman • Edited

The synonym for monad is callback. You can start by thinking of JS promises where you specify callbacks based on the future result state. However, JS promises are actually a monad (success or failure) within a monad (evaluated or not yet evaluated). Some languages represent these as separate concepts that you can combine yourself.

Another kind of monad is nullability. For example, C# has ?. to only access a property or call a method on an object if it is not null.

int? x = someObj?.IntProperty;
// vs
int x = someObj.IntProperty; // throws when someObj null

Typed FP languages usually make you explicitly represent nullability with Maybe or Option types and otherwise disallow it... so you don't have null guard clauses everywhere, but you are required to handle null cases where you have explicitly allowed it.

Other things can also be represented as monads, such as Lists (run a callback for each item in the list -- like Array.map in JS).

I assume you are not interested in the precise mathematical definition. Because most of what I said above is not that, although true in spirit. Also many attempts by OO languages to use monads seem to mix different operations. For example, ?. in C# accepts return values that are nullable (reference types) and not nullable (value types). In FP, these are considered two different operations: flatMap and map. For a perhaps more-relateable illustration of the difference, compare JS Array.flatmap vs Array.map.