Skip to content

Instantly share code, notes, and snippets.

@Demonstrandum
Created June 3, 2020 20:16
Show Gist options
  • Save Demonstrandum/881918fa9527565eee9547c36e07a7f2 to your computer and use it in GitHub Desktop.
Save Demonstrandum/881918fa9527565eee9547c36e07a7f2 to your computer and use it in GitHub Desktop.
Tacit programming with Currying and Composition in Python.
# # Exaple:
# ```py
# from tacit import *
#
# @fn
# def f(x, y):
# return 2 * (x + y)
#
# @fn
# def g(x): return x + 3
#
# a = (f(5) * g)(3) #=> 22
# b = f(7)(4) #=> 22
# ```
from functools import partial, reduce
class Fn(object):
def __init__(self, λ, curry=True):
self.curry = curry
self.λ = λ
def compose(*fns):
if len(fns) < 2:
raise Exception("Compose needs at least two arguments.")
fn1, fn2, *fns_tail = fns
if len(fns_tail) == 0:
return lambda x: fn1(fn2(x))
return lambda x: fn1(
self.__class__.compose(*([fn2] + fns_tail))(x))
def __mul__(self, other):
return self.compose(other)
def __call__(self, *arg):
if self.curry:
part = partial(self.λ, arg[0])
try:
if callable(part):
return part()
else:
return part
except TypeError:
return Fn(part, True)
return self.λ(*arg)
def fn(f):
return Fn(f)
def fn_curried(f):
return Fn(f, False)
def fn_curry(f):
return Fn(f, True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment