Python note three: Functional programming

Source: Internet
Author: User
Tags abs

1. Concept:

Functional programming is a very http://i.cnblogs.com/EditPosts.aspx?opt=1 high-level programming paradigm, the purely functional programming language functions do not have variables, so any function, as long as the input is OK, the output is OK, This pure function we call no side effects. In the case of programming languages that allow the use of variables, because of the variable state inside the function, the same input may get different output, so this function has side effects.

One of the features of functional programming is that it allows the function itself to be passed as a parameter to another function, and also allows a function to be returned! Python provides partial support for functional programming. Because Python allows the use of variables, Python is not a purely functional programming language.

2. Higher order functions: One function can receive another function as an argument, and this function is called the higher order function.

1) A variable can point to a function: The function itself can also be assigned to a variable, namely: A variable can point to a function

  f = abs

  >>> f(-10)

2) The function name is also a variable:

  abs = 10

  >>> abs(-10)出错

absafter the pointer 10 is pointed, it cannot be abs(-10) called by the function! Because abs this variable does not point to the absolute value function!

3) Incoming function:

  def add(x, y, f):

    return f(x) + f(y)

4) Map/reduce:

  map()The function receives two parameters, one is a function, the other is a sequence, the map incoming function functions sequentially to each element of the sequence, and returns the result as a new list. map()as a higher-order function, it abstracts the arithmetic rules.

Example: Implementing X*x

  def f(x):

    return x * x

>>>map (f,[1,2,3,4,5])

[1, 4, 9, 16, 25]

Reduce () functions a function in a sequence [X1, x2, x3 ...] , the function must receive two parameters, and reduce accumulates the result and the next element of the sequence.

  即reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4)

  def fn(x, y):

    return x * 10 + y

>>>reduce(fn, [1, 3, 5, 7, 9])

13579

5) Filter:

  filter()Functions are used to filter the sequence, to filter() receive a function and a sequence, to filter() Act on each element in turn, and then to True decide whether to False retain or discard the element based on the return value.

  def is_odd(n):

    return n % 2 == 1

  >>>filter(is_odd, [1, 2, 4, 5, 6, 9, 10, 15])

  [1, 5, 9, 15]

6) Sorted:

  def reversed_cmp(x, y):

    if x > y:

      return -1

    if x < y:

      return 1

  return 0

>>>sorted([36, 5, 12, 9, 21], reversed_cmp)

3. Return function: The higher order function can also return the function as the result value, in addition to the function as a parameter.

1) function as return value:

  def lazy_sum(*args):

    def sum():

      ax = 0

      for n in args:

        ax = ax + n

      return ax

  return sum

2) Closures:

The returned function references a local variable within its definition, args so when a function returns a function, its internal local variables are also referenced by the new function. One thing to keep in mind when returning closures is that the return function does not refer to any loop variables, or to subsequent variables that change.

4.LAMBDA:

  lambdaRepresents the anonymous function, which represents the function parameter before the colon, that x is, there can be only one expression, without writing return , and the return value is the result of the expression.

>>>map(lambda x: x * x, [1, 2, 3, 4, 5, 6, 7, 8, 9])

5. Adorner: Suppose we want to enhance 某个 the function of functions, for example, automatically print the log before and after the function call, but do not want to modify the definition of the function, this way in the code to dynamically increase the functionality of the mode, called "Adorner" (Decorator).

  def now():

    print ‘2013-12-25‘

>>>now.__name__  #可以获得函数名

  def log(func):

    def wrapper(*args, **kw):

      print ‘call %s():‘ % func.__name__

      return func(*args, **kw)

    return wrapper

  @log

  def now():

    print ‘2013-12-25‘

6. Partial function:

  functools.partial(): To fix some parameters of a function (that is, to set a default value), to return a new function, it would be easier to call the new function.

Python note three: Functional programming

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.