# 深入解析python中的lambda表达式的用法

0 := λf.λx.x
1 := λf.λx.f x
2 := λf.λx.f (f x)
3 := λf.λx.f (f (f x))

0 -> num0(f,x)=x
1 -> num1(f, x)=f(x)
2 -> num2(f,x)=f(f(x))
3 -> num3(f,x)=f(f(f(x)))

0是自然数， 度娘说1993年后，国家规定0是属于自然数。

num0=lambda f: lambda x:x
succ=lambda n: lambda f: lambda x: f(n(f)(x))

################################################
#define number calculus rules
################################################
#define church numeral inductively.
#0 := λf.λx.x
#1 := λf.λx.f x
#2 := λf.λx.f (f x)
#3 := λf.λx.f (f (f x))
#…
num0=lambda f: lambda x:x
succ=lambda n: lambda f: lambda x: f(n(f)(x))
#define operator
plus=lambda m: lambda n: m(succ)(n)
mult= lambda m: lambda n: m(plus(n))(num0)
#define predecessor to obtain the previous number.
pred= lambda n: lambda f: lambda x: n(lambda g: lambda h: h(g(f)))(lambda u:x)(lambda u:u)
sub=lambda m: lambda n: n(pred)(m)
pow=lambda b: lambda e: e(b)

################################################
#create encoder to input/output church numeral
################################################
class lambdaencoding:
@staticmethod
def encoding(exp,encoder):
return encoder().encoding(exp)
@staticmethod
def decoding(s, decoder):
return decoder().decoding(s)
class numencoder:
def encoding(self,num):
f=lambda x:x+1
return str(num(f)(0))
def decoding(self,s):
n=int(s)
num=num0
for i in range(n):
num=succ(num)
return num

################################################
#calculus demo
################################################
print(“demo number calculus.\n”
“don’t input large number,”
“it will cause to exceed maximum recursion depth!\n”)
n1=input(‘input a number: ‘)
n2=input(‘input anohter number: ‘)
#decode string to church numeral
num1=lambdaencoding.decoding(n1,numencoder)
num2=lambdaencoding.decoding(n2,numencoder)
#add
result=plus(num1)(num2)
print(‘{0} + {1} = {2}’.format(
n1,
n2,
lambdaencoding.encoding(result, numencoder)))
#mult
result=mult(num1)(num2)
print(‘{0} x {1} = {2}’.format(
n1,
n2,
lambdaencoding.encoding(result, numencoder)))
#sub
result=sub(num1)(num2)
print(‘{0} – {1} = {2}’.format(
n1,
n2,
lambdaencoding.encoding(result, numencoder)))
#pow
result=pow(num1)(num2)
print(‘{0} ^ {1} = {2}’.format(
n1,
n2,
lambdaencoding.encoding(result, numencoder)))

>>>
demo number calculus.
don’t input large number,it will cause to exceed maximum recursion depth!
input a number: 4
input anohter number: 3
4 + 3 = 7
4 x 3 = 12
4 – 3 = 1
4 ^ 3 = 64
>>>

lambda和def的区别
python lambda是在python中使用lambda来创建匿名函数，而用def创建的方法是有名称的，除了从表面上的方法名不一样外，python lambda还有哪些和def不一样呢？
1 python lambda会创建一个函数对象，但不会把这个函数对象赋给一个标识符，而def则会把函数对象赋值给一个变量。
2 python lambda它只是一个表达式，而def则是一个语句。

lambda x: print x

info = [lamba a: a**3, lambda b: b**3]

1单个参数的：

g = lambda x:x*2
print g(3)

m = lambda x,y,z: (x-y)*z
print m(3,1,2)

Posted in 未分类