Skip to content

Instantly share code, notes, and snippets.

@haryp2309
Created February 20, 2024 21:40
Show Gist options
  • Save haryp2309/bf3eb8bc7335e02da544a6243f49be42 to your computer and use it in GitHub Desktop.
Save haryp2309/bf3eb8bc7335e02da544a6243f49be42 to your computer and use it in GitHub Desktop.
Functional Programming In Python3.11+
from functional import Functional
import numpy as np
# Results in a NDArray[int_]
out = (
Functional[str](["hei", "boo", "1", "2", "4"])
.filter(lambda x: x.isnumeric())
.map(lambda x: int(x))
.enumerate()
.map(lambda v: v[0] + v[1])
.to(lambda x: np.fromiter(x, np.int_))
)
# Results in a list[int]
out = (
Functional[str](["hei", "boo", "1", "2", "4"])
.filter(lambda x: x.isnumeric())
.map(lambda x: int(x))
.enumerate()
.map(lambda v: v[0] + v[1])
.to_list()
)
from typing import Callable, Generic, Iterable, TypeVar
T = TypeVar("T")
MapReturnValue = TypeVar("MapReturnValue")
ToReturnValue = TypeVar("ToReturnValue")
class Functional(Generic[T]):
def __init__(self, gen: Iterable[T]) -> None:
self.__gen = gen
def enumerate(self):
return Functional(enumerate(self.__gen))
def map(self, function: Callable[[T], MapReturnValue]):
gen = (function(v) for v in self.__gen)
return Functional(gen)
def filter(self, function: Callable[[T], bool]):
gen = (v for v in self.__gen if function(v))
return Functional(gen)
def gen(self):
return self.__gen
def to(self, function: Callable[[Iterable[T]], ToReturnValue]):
return function(self.__gen)
def to_list(self):
return list(self.__gen)
def to_tuple(self):
return tuple(self.__gen)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment