Friday, June 17, 2011

A Peculiar Numbering System

Using the partial function application and composition from the previous post, we can represent the natural numbers in an interesting way.

def partial(f, *p):
    return lambda *q: f(*(p + q))

def compose(*fs):
    return lambda x: reduce(lambda a,b: b(a), (fs+(x,))[::-1])

def represent(n):
    return compose(*(partial(int.__add__, 1),) * n)(0)

assert represent(0) == 0
assert represent(1) == 1
assert represent(1337) == 1337

The nth natural number is the function λx.x+1 composed with itself n times, applied onto the number 0.

This is related to the concept of Church numerals.