码迷,mamicode.com
首页 > 编程语言 > 详细

python中lambda的另类使用

时间:2014-05-18 03:48:34      阅读:262      评论:0      收藏:0      [点我收藏+]

标签:lambda   编码   递归   python   

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的另类使用

标签:lambda   编码   递归   python   

原文地址:http://blog.csdn.net/pandora_madara/article/details/26064241

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!