Functional Programming:
Features: The arguments that are allowed to be passed are functions and allow a function to be returned.
Because Python allows the use of variables, Python is not a purely functional programming language, and the same input may have different output and side effects. Purely functional programming languages have no variables, inputs and outputs are deterministic and have no side effects.
1. Higher-order functions (Higher-order function):
Features: higher-order functions can accept another function as a parameter
Variables can point to functions, and function names are variables, so you can pass in functions as arguments.
1.1 Built-in functions:
Map (func, *iterables)
Reduce (function, sequence, initial=none)
#The process of iterating through a function returns a new iterator, which is a mapping. List (map (str, [1, 2, 3, 4, 5, 6, 7, 8, 9])) #return [' 1 ', ' 2 ', ' 3 ', ' 4 ', ' 5 ', ' 6 ', ' 7 ', ' 8 ', ' 9 '] #cumulative calculation: Converting sequences [1, 3, 5, 7, 9] to integers 13579 fromFunctoolsImportReducedeffn (x, y):returnX * 10 +y Reduce (FN, [1, 3, 5, 7, 9]) #13579 #combination of map () and reduce (): Str ' 13579 ' converted to int:13579 defChar2num (s):return{'0': 0,'1': 1,'2': 2,'3': 3,'4': 4,'5': 5,'6': 6,'7': 7,'8': 8,'9'8 {}[s] Reduce (FN, map (Char2num,'13579'))
#organized into a function str2int, these functions can also be written with an anonymous function because of a sentence fromFunctoolsImportReducedefStr2Int (s):deffn (x, y):returnX * 10 +ydefChar2num (s):return{'0': 0,'1': 1,'2': 2,'3': 3,'4': 4,'5': 5,'6': 6,'7': 7,'8': 8,'9': 9}[s]returnReduce (FN, map (Char2num, s))
Python, functional programming