Python BASICS (14): functional programming, 2015 python

Source: Internet
Author: User

Python BASICS (14): functional programming, 2015 python

I forgot to post this article. Make up now.

 

 

Python is not and is unlikely to become a functional programming language, but it supports the construction of many valuable functional programming languages.
There are also some functional programming mechanisms, but they are not traditionally considered to be the construction of functional programming languages. Python provides built-in functions and lambda expressions.

Anonymous functions and lambda

lambda [arg1, [arg2, ... argN]]:expression

Python allows the use of lambda keywords to create anonymous functions. Anonymous is because it does not need to be declared in a standard way. However, as functions, they can also have parameters. A complete lambda "statement" represents an expression. The definition body of this expression must be in the same line as the declaration. The parameter is optional. If a parameter is used, the parameter is usually part of the expression.
The following example shows the similarities between a single-line statement and a lambda statement:

>>> def true():    return True>>> true()True>>> lambda :True<function <lambda> at 0x02BDA430>>>> fun = lambda :True>>> fun()True

The following are some usage differences of expressions:

Def add (x, y): return x + ylambda x, y: x + ydef usuallyAdd2 (x, y = 2): return x + y # There are default parameters lambda x, y = 2: x + ydef showAllAsTuple (* z): return zlambda * z: z

Lambda expressions work like a function. When called, a framework object is created. After assigning a value to an object, the object is the corresponding function.

 

 

Built-in functions
Filter ()
Given an Object Sequence and a filter function, each sequence element is filtered by this filter, and the returned result is a real object.
If we want to write filter () by ourselves, it is probably like this:

def filter(bool_func, seq):
  filtered_seq = []  for eachItem in seq:    if bool_func(eachItem):      filtered_seq.append(eachItem)  return filtered_seq


Map ()
Map () built-in functions are similar to filter () because they can also process sequences through functions. However, unlike filter (), map () maps function calls to the elements of each sequence and returns a list containing all returned values.
If we want to write map () by ourselves, it is probably like this:

def map(func, seq):  mapped_seq = []  for eachItem in seq:    mapped_seq.append(func(eachItem))  return mapped_seq

 

Reduce ()
Reduce () uses a binary function, a sequence, and an optional initiator to effectively reduce the content of that list into a single value, just like its name. In other languages, this concept is called folding.
It extracts the first two elements of a sequence and passes them into a binary function to obtain a single value. Then, it uses this value and the next element of the sequence to obtain another value, then, the whole sequence is traversed and the final value is calculated.
If we want to write reduce () by ourselves, it is probably like this:

def reduce(bin_func, seq, init=None):  Iseq = list(seq) # convert to list  if init is None: # initializer?    res = lseq.pop(0) # no  else:     res = init # yes  for item in lseq: # reduce sequence    res = bin_func(res, item) # apply function  return res # return result

 


Partial function applications
Partial function application (PFA) converts any number of (sequential) parameter functions into another function object with residual parameters.
This concept is related to the concept of currying. currying, that is, corryization, refers to converting functions that originally accept multiple parameters into functions that accept a single parameter, and return the technology of the new function that accepts the remaining parameters and returns results.
This is somewhat abstract. We can think that the default parameters are similar if this parameter is not provided. In the PFA example, the parameter does not need to call the default value of the function, but only needs to explicitly call the set.
Example:

>>> from operator import add,mul>>> from functools import partial>>> add1 = partial(add,1)>>> add1(10)11>>> mul100 = partial(mul, 100)>>> mul100(5)500

The above called partial function is boring and does not show the power of partial function, but it allows us to know how to use it. When calling a function with many parameters, PFA is the best method.

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.