One feature of functional programming is that it allows the function itself to be passed as a parameter to another function, and also allows the return of a function
Http://www.liaoxuefeng.com/wiki/001374738125095c955c1e6d8bb493182103fac9270762a000/ 001386819196283586a37629844456ca7e5a7faa9b94ee8000
Function
Defining functions
def my_abs (x):
If x >= 0:
return x
Else
Return-x
Result =my_abs (10)
Print (Result)
Advanced Features
Slice
Slice
L[:3]
Iteration
D = {' A ': 1, ' B ': 2, ' C ': 3}
For key in D:
Print key #注意这个缩进 instead of {}
For ch in ' ABC ':
Print Ch
For x, y in [(1, 1), (2, 4), (3, 9)]:
Print x, y
Function-Type programming
One feature of functional programming is that it allows the function itself to be passed as a parameter to another function, and also allows the return of a function
Python provides partial support for functional programming. Because Python allows the use of variables, Python is not a purely functional programming language.
def add (x, Y, f):
return f (x) + f (Y)
Print Add ( -5, 6, ABS)
Results: 11
By passing functions as parameters, such functions are called higher-order functions, and functional programming refers to this highly abstract programming paradigm.
Map/reduce
If you read Google's famous paper "Mapreduce:simplified Data processing on Large Clusters", you can probably understand the concept of map/reduce.
map
Functions the passed-in function sequentially to each element of the sequence and returns the result as a new list.
Reduce functions a function in a sequence [X1, x2, x3 ...] , the function must receive two parameters, and reduce calculates the result and the next element of the sequence, and the effect is:
#map
def f (x):
return x * x
Print map (f, [1, 2, 3, 4, 5, 6, 7, 8, 9])
#reduce
DEF fn (x, y):
Print x, y, × * + Y
return x * ten + y
Print reduce (FN, [1, 3, 5, 7, 9])
filter()
Also receives a function and a sequence. and map()
different, the filter()
incoming function is applied sequentially to each element, and then True
False
the element is persisted or discarded based on the return value.
def is_odd (n):
return n% 2 = = 1
Print filter (is_odd, [1, 2, 4, 5, 6, 9, 10, 15])
IO programming
Read the file
f = open (' D:\logs\log.txt ', ' R ')
Print F.read ()
Write a file
f = open ('/users/michael/test.txt ', ' W ')
F.write (' Hello, world! ')
F.close ()
# #-*-Coding:utf-8-*-
__author_= ' Yuchao '
Print "Hello world!"
Must be placed on the first line
TCP Programming
#
# #-*-Coding:utf-8-*-
# Import the Socket library:
Import socket
# Create a socket:
s = socket.socket (socket.af_inet, socket. SOCK_STREAM)
# to establish a connection:
S.connect (' m.yintai.com ', 80)
While True:
data = S.RECV (1024)
Getting started with Python-functional programming