首页 > 代码库 > python中lambda的另类使用
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 ) )‘ )
python中lambda的另类使用
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。