python中lambda的另类使用

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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的另类使用的主要内容,如果未能解决你的问题,请参考以下文章

❤️另类工作照|工作中用Python自拍后回传到邮箱!❤️

Python装饰器的另类用法

python中对列表浅复制深复制另类的理解方式

python中lambda使用

使用 savedInstanceState 保存和恢复 Kotlin lambda

在 python 3 中使用 map 和 lambdas,为啥这段代码不会更新 sql 表