Skip to content

Instantly share code, notes, and snippets.

@esehara esehara/l.py
Created Jan 21, 2015

Embed
What would you like to do?
型なしラムダを実装する的なやつの途中まで from 『アンダースタンディング・コンピュテーション』より
# -*- coding: utf-8 -*-
from __future__ import print_function
# Primitive
ZERO = lambda f: lambda x: x
ONE = lambda f: lambda x: f(x)
TWO = lambda f: lambda x: f(f(x))
THREE = lambda f: lambda x: f(f(f(x)))
# Pair
PAIR = lambda x: lambda y: lambda f: f(x)(y)
LEFT = lambda p: p(lambda x: lambda y: x)
RIGHT = lambda p: p(lambda x: lambda y: y)
# Calc
INC = lambda n: lambda p: lambda x: p(n(p)(x))
SLIDE = lambda p: PAIR(RIGHT(p))(INC(RIGHT(p)))
DEC = lambda n: LEFT(n(SLIDE)(PAIR(ZERO)(ZERO)))
TRUE = lambda x: lambda y: x
FALSE = lambda x: lambda y: y
# Syntax
OLD_IF = lambda f: lambda x: lambda y: f(x)(y)
IF = lambda f: f
IS_ZERO = lambda n: n(lambda x: FALSE)(TRUE)
# Lambda -> Any Types
lambda_int = lambda f: f(lambda x: x + 1)(0)
lambda_bool = lambda f: IF(f)(True)(False)
print(lambda_int(ZERO))
print(lambda_int(TWO))
print(lambda_int(THREE))
print(lambda_bool(TRUE))
print(lambda_bool(FALSE))
print(IF(TRUE)('はい')('いいえ'))
print(IF(FALSE)('はい')('いいえ'))
print(lambda_bool(IS_ZERO(ZERO)))
print(lambda_bool(IS_ZERO(TWO)))
my_pair = PAIR(THREE)(ZERO)
my_pair_two = PAIR(PAIR(ZERO)(TWO))(ONE)
print(lambda_int(LEFT(my_pair)))
print(lambda_int(RIGHT(my_pair)))
print(lambda_int(LEFT(LEFT(my_pair_two))))
print(lambda_int(RIGHT(my_pair_two)))
print(lambda_int(INC(THREE)))
print(lambda_int(DEC(TWO)))
print(lambda_int(DEC(ONE)))
print(lambda_int(DEC(DEC(TWO))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.