Python Basic notes: Functional Programming: higher-order functions, return functions, anonymous functions, adorners, partial functions

Source: Internet
Author: User
Tags closure for in range

Higher order functions

Higher order function: A function can receive another function as a parameter or a function can return a function as a return value, which is called a higher order function.

# function add receives the F function as a parameter def Add (x,y,f):      ... return f (x) +f (y) ... >>> Add ( -5,6, ABS)11

The anonymous function can be returned as a return value

# returns the anonymous function as a return value def build (x, y):     return Lambda: x * x + y * y

anonymous functions

The keyword lambda represents the anonymous function, and the x preceding the colon represents the function parameter

 >>> list (map lambda  x:x*x,list (range (1,10  1, 4, 9, (+), +,,, 81]  def   f (x):  return  x*x  >>> from  Hello import   f  >>> list (map (lambda  x:x*x,list (range (1,10 1, 4, 9, 16, 25, 36, 49, 64, 81< Span style= "COLOR: #000000" > " #   These two methods are equivalent, But the first type of code is even less. 
def f (x):     return x*x# equivalent to Lambda x:x*x

return function

For example, we implement a summation function:

def calc_sum (*args):    ans=0    for in  args:        ans+=    Ireturn ans

But what if you don't need to sum it right away, but in the later code, and then calculate it as needed?

Instead of returning the result of a sum, you can return a function that sums:

def lazy_sum (*args):    def  sum ():        ans=0        for  in args:            ans+=        Ireturn     ansreturn sum
# Call >>> l=list ( The function returned by the range 1,11 # is not executed immediately, but until the F >>> is called f ()55

In this example, we define the function sum in the function lazy_sum, and the inner function sum can refer to the parameters and local variables of the external function lazy_sum, and when Lazy_sum returns the function sum, the relevant parameters and variables are stored in the returned function, which is called "Closure ( Closure) "has great power in its program structure.

When we call Lazy_sum (), each call will return a new function, even if the same parameters are passed in:

>>> f1=lazy_sum (*l)>>> f2=lazy_sum (*l)>>> f1==f2false

An example of a "closure":

def count ():    fs=[]    for in# Each loop creates a new function and then returns the 3 functions that were created         def  F ():            return i*i        fs.append (f)      Return FS
# call >>> f1,f2,f3=>>> F1 ()9>>> f2 ()9>> > f3 ()9

Why is it all 9?!

The reason is that the returned function refers to the variable I, but it is not executed immediately. When all three functions return, they refer to the variable i has become 3, so the final result is 9 ...

What if you must refer to a loop variable? The method is to create a function that binds the current value of the loop variable with the parameter of the function, regardless of how the loop variable is subsequently changed, and the value that is bound to the function parameter remains the same:

def count ():    fs=[]    for in range (1,4):         def  F (i) :            def  g ():                return i*i            return  g        Fs.append (f (i))     return FS
# called  from Import count>>> f1,f2,f3=count ()>>> F1 ()1>>> f2 ()4> >> f3 ()9

Use the lambda function to simplify:

def count ():    fs=[]    for in range (1,4):         def  F (i) :            returnlambda : i*i        fs.append (f (i))    return FS

Exercise: Use a closure to return a counter function that returns an incremented integer each time it is called

def count_num ():    f=[0]    def  count ():        f[0]=f[0]+1        return F[0]     return Count
 from Import count_num>>> f=count_num ()>>> f ()1>>> F ()2 >>> F ()3>>>

Higher order function--map

The map () function receives two parameters, one is the function, the other is iterable, and the map takes the break-in function to each element of the sequence at once, and returns the result as a new Iterator.

Using map to implement a function f (x) =x*x, acting on a list after the result output:

>>> L=range (1,11)>>> l=list (range (1,11))>>> r=map (Lambda x:x *x,l)>>> list (R) [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

Higher order function--reduce

The reduce () function takes two parameters and uses the function most in a sequence, and reduce calculates the result and the next element of the sequence in a cumulative way, with the effect of:

Reduce (f, [X1, x2, X3, x4]) = f (f (f (x1, x2), x3), x4)

Using reduce to achieve sequence summation

 from Import # use the Reduce function first import>>> l=list (range 1,11)>>> reduce (lambda x,y:x+ y,l) 55

Using the reduce implementation to turn an integer sequence into an integer

>>> l=list (Range (1,10))>>> reduce (lambda x,y:x*10+y,l)123456789

Using reduce + map to implement the function of STR to int

>>>defChar_num (c): ... digits={'0'70A'1': 1,'2': 2,'3': 3,'4': 4,'5'75A'6': 6,'7': 7,'8': 8,'9': 9}...     returnDigits[c] ...>>> Reduce (LambdaX,y:x*10+y,list (Map (Char_num,'13654')))13654

Python has a built-in function for the interaction of STR and INT

>>> Str (4515)'4515'>>> int ('5252')  )5252

Exercise: The use map() of functions, the user entered the non-standard English name, the first letter uppercase, other lowercase canonical name. Input: [‘adam‘, ‘LISA‘, ‘barT‘] , output: [‘Adam‘, ‘Lisa‘, ‘Bart‘] :

Python Basic notes: Functional Programming: higher-order functions, return functions, anonymous functions, adorners, partial functions

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.