Process for the functional programming

Common programming paradigm: process-oriented, functional, and other object-oriented

A. Process-oriented

"Process-oriented" core "process" the word "process" refers to the steps to resolve the problem, which is to do and then what ......, based on process-oriented development process is like designing a pipeline, a mechanical way of thinking, it just fit the computer's operating principle: the implementation of any program eventually need to be converted into cpu scheduling process according to the instruction pipeline execution, regardless of what language that is, no matter what kind of programming paradigm based on the design of the program, the final the execution of all procedural. Specifically, if the program is beginning to tackle a big problem, in accordance with the procedural thinking this is a big problem into many small problems or sub-processes to achieve, then we can turn call, which greatly reduces the complexity of the program.

举例:写一个数据远程备份程序,分三步:本地数据打包,上传至云服务器,检测备份文件可用性

import os,time

# 一:基于本章所学,我们可以用函数去实现这一个个的步骤
# 1、本地数据打包
def data_backup(folder):
    print("找到备份目录: %s" %folder)
    print('正在备份...')
    zip_file='/tmp/backup_%s.zip' %time.strftime('%Y%m%d')
    print('备份成功,备份文件为: %s' %zip_file)
    return zip_file

#2、上传至云服务器
def cloud_upload(file):
    print("\nconnecting cloud storage center...")
    print("cloud storage connected")
    print("upload [%s] to cloud..." %file)
    link='https://www.xxx.com/bak/%s' %os.path.basename(file)
    print('close connection')
    return link

#3、检测备份文件可用性
def data_backup_check(link):
    print("\n下载文件: %s , 验证文件是否无损..." %link)


#二:依次调用
# 步骤一:本地数据打包
zip_file = data_backup(r"/Users/egon/欧美100G高清无码")

# 步骤二:上传至云服务器
link=cloud_upload(zip_file)

# 步骤三:检测备份文件的可用性
data_backup_check(link)

Process-oriented summary:

1、优点
将复杂的问题流程化,进而简单化

2、缺点
程序的可扩展性极差,因为一套流水线或者流程就是用来解决一个问题,就好比生产汽水的流水线无法生产汽车一样,即便是能,也得是大改,而且改一个组件,与其相关的组件可能都需要修改,比如我们修改了cloud_upload的逻辑,那么依赖其结果才能正常执行的data_backup_check也需要修改,这就造成了连锁反应,而且这一问题会随着程序规模的增大而变得越发的糟糕。


def cloud_upload(file): # 加上异常处理,在出现异常的情况下,没有link返回
    try:
        print("\nconnecting cloud storage center...")
        print("cloud storage connected")
        print("upload [%s] to cloud..." %file)
        link='https://www.xxx.com/bak/%s' %os.path.basename(file)
        print('close connection')
        return link
    except Exception:
        print('upload error')
    finally:
        print('close connection.....')

def data_backup_check(link): # 加上对参数link的判断
    if link:
        print("\n下载文件: %s , 验证文件是否无损..." %link)
    else:
        print('\n链接不存在')
        
3、应用场景
面向过程的程序设计一般用于那些功能一旦实现之后就很少需要改变的场景, 如果你只是写一些简单的脚本,去做一些一次性任务,用面向过程去实现是极好的,但如果你要处理的任务是复杂的,且需要不断迭代和维护, 那还是用面向对象最为方便。

2. Functional

Functional programming with functional programming is not so simple, but the operation is regarded as a computer operator in the mathematical sense, than process-oriented, functional, pay more attention to the implementation process rather than the result of the implementation, on behalf languages: Haskell, Erlang . The python is not a functional programming language, but we still provide a lot of good functional programming features such as lambda, map, reduce, filter

2.1 anonymous functions and lambda
contrast to the def keyword is created with the name of the function, using the lambda keyword creation is a function without a name, that anonymous function syntax is as follows

lambda 参数1,参数2,...: expression
# 1、定义
lambda x,y,z:x+y+z

#等同于
def func(x,y,z):
    return x+y+z

# 2、调用
# 方式一:
res=(lambda x,y,z:x+y+z)(1,2,3)

# 方式二:
func=lambda x,y,z:x+y+z # “匿名”的本质就是要没有名字,所以此处为匿名函数指定名字是没有意义的
res=func(1,2,3)

Anonymous functions and named functions have the same scope, but anonymous means that the reference count is 0, once it is released, so anonymous function for the temporary use of a scene, usually with an anonymous function with other functions use.

salaries={
    'siry':3000,
    'tom':7000,
    'lili':10000,
    'jack':2000
}

要想取得薪水的最大值和最小值,我们可以使用内置函数max和min

>>> max(salaries)
'tom'
>>> min(salaries)
'jack'

内置max和min都支持迭代器协议,工作原理都是迭代字典,取得是字典的键,因而比较的是键的最大和最小值,而我们想要的是比较值的最大值与最小值,于是做出如下改动

# 函数max会迭代字典salaries,每取出一个“人名”就会当做参数传给指定的匿名函数,然后将匿名函数的返回值当做比较依据,最终返回薪资最高的那个人的名字
>>> max(salaries,key=lambda k:salaries[k]) 
'lili'
>>> min(salaries,key=lambda k:salaries[k])
'jack'

同理,我们直接对字典进行排序,默认也是按照字典的键去排序的

>>> sorted(salaries)
['jack', 'lili', 'siry', 'tom']

2.2 map、reduce、filter

Function map, reduce, filter support iterator protocol for processing iterables.

array=[1,2,3,4,5]

Column 1: made for each element of the square array processing, can use the map function
map function takes two parameters, a function, a further iteration is the object, it is used as follows

>>> res=map(lambda x:x**2,array)
>>> res
<map object at 0x1033f45f8>
>>>

PS: map will be followed by an iterative array, the value obtained in order to pass an anonymous function (can also be a named function), and the results obtained by the map function is still iterator.

>>> list(res) #使用list可以依次迭代res,取得的值作为列表元素
[1, 4, 9, 16, 25]

Column 2: The merge operation array, such as summation, which uses the reduce function
reduce function can receive three parameters, it is a function, the second iteration is an object, the third initial value

# reduce在python2中是内置函数,在python3中则被集成到模块functools中,需要导入才能使用
>>> from functools import reduce 
>>> res=reduce(lambda x,y:x+y,array)
>>> res
15

PS: no initial value, the reduce function will iterate a first array obtained as an initial value, as the number of values ​​to the first x, then continue iterating a value obtained as the second array values ​​to the y, the result of the operation 3, the results of the last operation as reduce first pass a value x, then the results of the iteration time array value obtained as the second pass y, and so on, these iterative know all the elements of the array to obtain a final result 15

You can also reduce initial values ​​are specified

>>> res=reduce(lambda x,y:x+y,array,100)
>>> res
115

Column 3: array of the filtering operation, which uses a filter function, such as a filter element is greater than 3

>>> res=filter(lambda x:x>3,array)

PS: filter function sequentially Array iteration, a value obtained by sequentially pass anonymous functions, anonymous function if the return value is true, then the element was filtered off, and the filter function of the results obtained is still iterator.

>>> list(res) 
[4, 5]

2.3 sorted、max、min

salaries={
    'siry':3000,
    'tom':7000,
    'lili':10000,
    'jack':2000
}

res=max(salaries,key=func) # 返回值=func('siry') 字典默认取key
print(res)

res=max(salaries,key=lambda k:salaries[k])
print(res) #lili

min
res=min(salaries,key=lambda k:salaries[k])
print(res) #jack


sorted
salaries={
     'siry':3000,
     'tom':7000,
     'lili':10000,
     'jack':2000
 }
res=sorted(salaries,key=lambda k:salaries[k],reverse=True)
print(res)

Guess you like

Origin www.cnblogs.com/chenwenyin/p/12573681.html