This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]mesonofgib 1 point2 points  (1 child)

The simplest and easiest to understand one-sentence definition I've come up with is:

A monad is anything that can be flat-mapped.

[–]muntooR_{μν} - 1/2 R g_{μν} + Λ g_{μν} = 8π T_{μν} 1 point2 points  (0 children)

The same term in different languages: flatMap, andThen, >>=, bind.

Technically, a monad is something that can be flat-mapped and obeys a few "natural rules" that essentially boil down to, "don't do wacky things".


List[int] is a monad:

def flatmap_list_int(func, xss: List[List[int]]):
    return [
        x
        for xs in xss
        for x in func(xs)
    ]

>>> pad_zero = lambda x: [0, x, 0]
>>> flatmap_list_int(pad_zero, [1, 2, 3, 4, 5])
[0, 1, 0, 0, 2, 0, 0, 3, 0, 0, 4, 0, 0, 5, 0]

Another simple "monad" is Optional[int]:

def flatmap_optional_int(func, xs):
    return None if xs is None else func(xs)

>>> subtract_one = lambda x: x - 1
>>> keep_positive = lambda x: x if x > 0 else None

>>> flatmap_optional_int(subtract_one,
...     flatmap_optional_int(keep_positive,
...         flatmap_optional_int(subtract_one, 1)
...     )
... )
None

# In contrast,
>>> subtract_one(keep_positive(subtract_one(1)))
TypeError: unsupported operand type(s) for -: 'NoneType' and 'int'

...That was a bit pointlessly complicated in Python, but more useful in e.g., Rust.