python中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 ) )' )