Skip to content

Instantly share code, notes, and snippets.

Last active October 30, 2022 19:19
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
List Monad in Python
"""A List Monad."""
from __future__ import annotations
from itertools import chain
from typing import Any as b
from typing import Callable as Function
from typing import Iterable as Functor
from typing import List
from typing import TypeVar
a = TypeVar("T")
concat = chain.from_iterable
class FunctorList(List[a]):
def fmap(fa, f: (a, b)) -> f[b]:
return FunctorList(map(f, fa))
class ApplicativeList(FunctorList):
def pure(a) -> m[a]:
return ApplicativeList(a)
def apply(fs, xs) -> f[b]:
return ApplicativeList([f(x) for f in xs for x in fs])
class MonadList(ApplicativeList):
def ret(a) -> m[a]:
return MonadList(a)
def __rshift__(xs, f: (a, m[b])) -> m[b]:
return MonadList(concat (map(f, xs)))
FunctorList([1, 2, 3])
.fmap(lambda x: x + 1)
.fmap(lambda x: str(x))
.fmap(lambda x: x + "0")
ApplicativeList([1, 2, 3])
.apply([(lambda x: x + 1)])
.apply([(lambda x: str(x))])
.apply([(lambda x: x + "0")])
MonadList([1, 2, 3])
>> (lambda x: [x + 1])
>> (lambda x: [str(x)])
>> (lambda x: [x + "0"])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment