Skip to content

Instantly share code, notes, and snippets.

@alexeymuranov
Last active December 13, 2018 13:14
Show Gist options
  • Save alexeymuranov/1c85afad835a1fc57b28f6533ffa77d9 to your computer and use it in GitHub Desktop.
Save alexeymuranov/1c85afad835a1fc57b28f6533ffa77d9 to your computer and use it in GitHub Desktop.
Carry's fixed-point fonction for transformations of functions
# Fixed-point function without explicit recursion:
def fix(f):
def self_applied(self_applied):
return f(wrap_selfappl(self_applied))
return wrap_selfappl(self_applied)
# Auxiliary function:
def wrap_selfappl(f):
def w(*args, **kwargs):
return f(f)(*args, **kwargs)
return w
# Fixed-point function with explicit recursion:
# XXX: cheating!
def fix_rec(f):
def a(*args, **kwargs):
return f(a)(*args, **kwargs)
return a
# ----
# Test
# ----
if __name__ == "__main__":
def rec_factorial_maker(f0):
def f(n):
if n == 0:
return 1
return n*f0(n - 1)
return f
fact = fix(rec_factorial_maker)
assert (fact(0), fact(1), fact(2), fact(3), fact(6)) == (1, 1, 2, 6, 720)
fact = fix_rec(rec_factorial_maker)
assert (fact(0), fact(1), fact(2), fact(3), fact(6)) == (1, 1, 2, 6, 720)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment