python中lambda的另类使用

Lambda挺强大,有兴趣的人看下关于lambda的理论,就清楚邱奇编码的实现了。

网上的都只是讲的千篇一律的匿名函数的简单用法,很没趣。

那些建议取消python中lambda的同志,知道lambda可以这么用么。


带if/else:

( lambda x, y: x if x < y else y )( 1, 2 )


科里化:

( lambda x: ( lambda y: ( lambda z: x + y + z  )( 1 ) )( 2 ) )( 3 )


递归:

func = lambda n: 1 if n == 0 else n * func( n - 1 )
func( 5 )

f = lambda func, n: 1 if n == 0 else n * func( func, n - 1 )
print f( f, 4 )

构建邱奇编码:

true = lambda x: lambda y: x

false = lambda x: lambda y: y

if_then_else = lambda a: lambda b: lambda c: ( a )( b )( c )

zero = lambda f: lambda x: x

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

one = succ( zero )

plus_one = lambda x: x + 1

add = ( lambda m: lambda n: lambda f: lambda x:
        n( f )( m( f )( x ) ) )

mult = ( lambda m: lambda n: lambda f: lambda x:
         n( m( f ) )( x ) )

exp = lambda m: lambda n: n( m )

church_numeral = lambda n: n( plus_one )( 0 )

natural_number_to_church = lambda num: zero if num == 0 else                            succ( natural_number_to_church( num - 1 ) )

execute = lambda s: s + ‘ = ‘ + str( eval( s ) )

print execute( ‘church_numeral( zero )‘ )
print execute( ‘church_numeral( succ( zero ) )‘ )
print execute( ‘church_numeral( add( one )( succ( one ) ) )‘ )
print execute( ‘church_numeral( mult( succ( one ) )( succ( one ) ) )‘ )
print execute( ‘church_numeral( exp( succ( succ( one) ) )( succ( one ) ) )‘ )

c200 = natural_number_to_church( 200 )
c222 = natural_number_to_church( 222 )

print execute( ‘church_numeral( add( c200 )( c222 ) )‘ )
print execute( ‘church_numeral( if_then_else( true )( zero )( one ) )‘ )
print execute( ‘church_numeral( if_then_else( false )( zero )( one ) )‘ )


python中lambda的另类使用,布布扣,bubuko.com

python中lambda的另类使用

上一篇:java多线程实验 滚动字


下一篇:ENSP桥接电脑物理网卡,实现web管理