Deep parsing of the use of lambda expressions in Python

Source: Internet
Author: User
Tags python list
Ordinary mathematical operations are defined by this purely abstract symbolic calculus, and the results can only be found in the brain. So write a bit of code to verify the calculation rules described in the article.

Let's verify the natural number and the natural number operation rules described in the article. Speaking of natural numbers, today also Baidu a bit, according to Niang said, 1993 years after the state stipulated 0 is the natural number. Define the rule of the natural number and the natural number first:

Defining natural numbers with lambda expressions (Chiuzi number)

0: =λf.λx.x1: =λf.λx.f X2: =λf.λx.f (F x) 3: =λf.λx.f (f (f x)) ...

The intuitive meaning of the above definition is the number n, which is the N-order function of f (x). 1 is f (x), and 2 is F (f (x)) ...., strictly speaking, this is not an accurate statement. In fact, each Chow kit number is a second-order function, which has two variables F and x. Using a two-dollar name function to express is:

0-NUM0 (f,x) =x1, NUM1 (f, x) =f (x) 2, num2 (f,x) =f (f (x)) 3, num3 (f,x) =f (f (f (x))) ...

Where parameter f is a function. This is a bit of a detour, but it doesn't make sense, and it's difficult to understand the lambda calculus behind it.

First, a recursive method is used to define the number of Chiuzi (natural number)

0 is the natural number, Degree Niang said 1993 years later, the state stipulates 0 is the natural number.

Each natural number has a follow-up.

Expression in code is:

Num0=lambda f:lambda x:xsucc=lambda n:lambda f:lambda x:f (n (f) (x))

The following are defined operators, including addition, multiplication, subtraction, and power. The wiki article does not introduce division, reckoned the definition of division is more complex, for a moment is unclear. Well, we're not verifying it either.

################################################ #define NUMBER Calculus rules#################################### ############ #define Church numeral inductively. #0: =λf.λx.x#1: =λf.λx.f x#2: =λf.λx.f (f x) #3: =λf.λx.f (f (f x)) #. . Num0=lambda f:lambda x:xsucc=lambda n:lambda f:lambda x:f (n (f) (x)) #define OPERATORPLUS=LAMBDA M:lambda n:m (SUCC) (n) mult= Lambda M:lambda n:m (PLUS (n)) (NUM0) #define predecessor to obtain the previous number. pred= Lambda N:lambda f:lambda x:n (Lambda G:lambda h:h (g (f))) (Lambda u:x) (lambda u:u) Sub=lambda m:lambda-N (PRED) ( m) Pow=lambda B:lambda e:e (b)

Defines what is the operator of natural and natural numbers. Then the calculation of the natural number can be computed in the form of lambda calculus.

The problem is that the above definitions are abstract symbolic calculus, we need to have an encoder to encode the above abstract church numeral symbols into a form that can be read by people, and to decode the numbers entered by people into abstract symbols.

################################################ #create encoder to Input/output Church numeral##################### ########################### class lambdaencoding:  @staticmethod  def encoding (exp,encoder):    return Encoder (). Encoding (exp)  @staticmethod  def decoding (S, decoder):    return Decoder (). Decoding (s)   Class Numencoder:  def encoding (self,num):    f=lambda x:x+1    return str (num (f) (0))  def decoding (self,s ):    N=int (s)    NUM=NUM0 for    i in range (n):      num=succ (num)    return num

Well, with the encoder, it can be easily verified.

################################################ #calculus demo################################################ Print ("Demo number calculus.\n" "   don t input large number,"   "it'll cause to exceed maximum recursion depth!\n") N1=input (' Input a number: ') n2=input (' Input anohter number: ') #decode string to Church numeralnum1= Lambdaencoding.decoding (N1,numencoder) num2=lambdaencoding.decoding (n2,numencoder)   #addresult =plus (NUM1) ( num2) print (' {0} + {1} = {2} '. Format (  N1,  n2,  lambdaencoding.encoding (result, numencoder)) #multresult = MULT (NUM1) (num2) print (' {0} X {1} = {2} '. Format (  N1,  n2,  lambdaencoding.encoding (result, Numencoder)) # Subresult=sub (NUM1) (num2) print (' {0}-{1} = {2} '. Format (  N1,  n2,  lambdaencoding.encoding (result, Numencoder))) #POWresult =pow (NUM1) (num2) print (' {0} ^ {1} = {2} '. Format (  N1,  N2,  Lambdaencoding.encoding (result, numencoder)))

The test results are as follows:

>>> demo number Calculus.don ' t input large number,it would cause to exceed maximum recursion depth! Input a number:4input anohter number:34 + 3 = 3 X = 124-3 = + 3 = 64>>>

Magic Bar.

The difference between Lambda and def
Python lambda is using lambda in Python to create anonymous functions, and the method created with Def is named, but what else does Python lambda have to do with Def, in addition to the method names on the surface?
1 Python lambda creates a function object, but does not assign the function object to an identifier, and Def assigns the function object to a variable.
2 Python Lambda It's just an expression, and DEF is a statement.
The following is a Python lambda format that looks good and streamlined.

Lambda X:print x

If you use Python lambda in the Python list parsing, I don't feel much of a thing because Python lambda creates a function object, but discards it immediately, because you're not using its return value, which is the function object. It is also because Lambda is just an expression that can be directly a member of a Python list or a Python dictionary, such as:

info = [Lamba a:a**3, Lambda B:b**3]

There is no way to replace the DEF statement directly in this place. Because DEF is a statement, not an expression that cannot be nested inside, a lambda expression can have only one expression after ":". That is, in Def, return can also be placed behind a lambda, and cannot be returned with return can not be defined behind a Python lambda. Therefore, a statement such as if or for or print cannot be used in a lambda, and lambda is generally used only to define simple functions.
Let's give some examples of Python lambda.
1 for single parameters:

g = Lambda X:x*2print g (3)

The result is 6.
For multiple parameters:

m = lambda x, y, Z: (x-y) *zprint m (3,1,2)

The result is 4.

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.