read

Monads can be confusing but they shouldn't be.

Monads from an OOP perspective are simply an interface with two methods. That is it.

Here is a working python example of two separate Monads, one for a list and one for an option type.

"""
interface Monad
    def return(val:T):M[T]

    def bind(val:M[T], f: func<T, M[T]>): M[T]
"""

class ListMonad:
    def __init__(self, val):
        self.val = val
    def bind(self, f):
        return ListMonad(sum([f(v) for v in self.val], []))

class OptionMonad:
    def __init__(self, val):
        self.val = val

    def bind(self, f):
        return OptionMonad(None) if self.val is None else f(self.val) 

"""
interface Functor
    def map(val:F[T1], f:func<T1, T2>):F[T2]
"""

class ListFunctor:
    def __init__(self, val):
        self.val = val

    def map(f):
        return map(f, self.val)

class OptionFunctor:
    def __init__(self, val):
        self.val = val

    def map(f):
        return OptionFunctor(None) if self.val is None else OptionFunctor(f(self.val))
Blog Logo

Grant Nicholas


Published