In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly introduces "how to master functional programming". In daily operation, I believe many people have doubts about how to master functional programming. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful for you to answer the doubts of "how to master functional programming"! Next, please follow the editor to study!
Programming paradigm
Programming paradigm refers to a programming style that describes the programmer's view of program execution. In the world of programming, the same problem can be analyzed and solved from multiple angles, and these different solutions correspond to different programming styles.
Common programming paradigms are:
Imperative programming
C
Process oriented programming
Object oriented programming
C++ 、 C# 、 Java
Declarative programming
Haskell
Functional programming
Imperative programming
Imperative programming is the most widely used programming style. it thinks about problems from the point of view of the computer. the main idea is to pay attention to the steps of computer execution, that is, telling the computer what to do first and then what to do step by step.
Because there are many steps to control, imperative programming generally has the following characteristics:
Control statement
Loop statements: while, for
Conditional branching statements: if else, switch
Unconditional branching statements: return, break, continue
Variable
Assignment statement
Based on these characteristics, let's analyze a case of imperative programming:
/ / requirements: filter out the odd subsets in the array const array = [1, 2, 3, 4, 5, 6, 7, 8, 9]; / / step 1: define the execution result variable let reult = []; / / step 2: control program loop call for (let I = 0; I)
< array.length; i++) { // 步骤3:判断筛选条件 if (array[i] % 2 !== 0) { // 步骤4:加入执行结果 reult.push(array[i]); } } // 步骤5:得到最终的结果 result 以上代码通过 5 个步骤,实现了数组的筛选,这并没有什么问题,但细心的同学可能会感到疑惑:这样写的代码量太长了,而且并不语义化,只有阅读完每一行的代码,才知道具体执行的是什么逻辑。 没错,这就是命令式编程的典型特点,除此之外,还有以下几点: 命令式编程的每一个步骤都可以由程序员定义,这样可以更精细化、更严谨地控制代码,从而提高程序的性能。 命令式编程的每一个步骤都可以记录中间结果,方便调试代码。 命令式编程需要大量的流程控制语句,在处理多线程状态同步问题时,容易造成逻辑混乱,通常需要加锁来解决。 声明式编程 声明式编程 同样是一种编程风格,它通过定义具体的规则,以便系统底层可以自动实现具体功能。主要思想是 告诉计算机应该做什么,但不指定具体要怎么做。 由于需要定义规则来表达含义,所以声明式编程普遍存在以下特点: 代码更加语义化,便于理解。 代码量更少。 不需要流程控制代码,如:for、while、if 等。 接下来,我们将上文中的数组筛选,用声明式的方式重构一下: // 筛选出数组中为奇数的子集合 const array = [1, 2, 3, 4, 5, 6, 7, 8, 9]; const reult = array.filter((item) =>Item% 2! = = 0)
As you can see, declarative programming has no redundant steps, has a very small amount of code, and is very semantic, so when we read filter, we naturally know that we are doing filtering.
Let's look at another case:
# use sql statement to query students with an id of 25
# use sql statement to query student select * from students where id=25 with an id of 25
In the above code, we just tell the computer that I want to find the classmate whose id is 25, and the computer can return the corresponding data to us. As for how to find it, we don't need to care, as long as the result is correct.
In addition to the above examples, there are many cases of declarative programming:
Html is used to declare the content of a web page.
Css is used to declare the appearance of elements in a web page.
A regular expression that declares matching rules.
With the above examples, let's summarize the advantages and disadvantages of declarative programming:
Declarative programming does not need to write complex operation steps, which can greatly reduce the workload of developers.
The specific operation of declarative programming is unified management at the bottom, which can reduce repetitive work.
The logic of the underlying implementation of declarative programming is not controllable and is not suitable for more refined optimizations.
Functional programming
Functional programming is a kind of declarative programming. Its main idea is to regard computer operation as the calculation of functions, that is, to abstract program problems into mathematical problems to solve.
In functional programming, we can make full use of mathematical formulas to solve problems. In other words, any question can be solved step by step through functions (addition, subtraction, multiplication and division) and mathematical laws (commutative law, association law, etc.).
In functional programming, all variables are unique values, just like algebras x and y in mathematics, they are either unsolved or have been solved to fixed values, so self-increment such as x=x+1 is illegal because it does not conform to mathematical logic by modifying algebraic values.
In addition, strictly functional programming does not include control statements such as loops and conditional judgments. if conditional judgment is needed, ternary operators can be used instead.
At the beginning of the article, we mentioned webpack-chain. Let's take a look at:
/ / use webpack-chain to write the webpack configuration. Const Config = require ('webpack-chain'); const config = new Config (); config. .entry ('index') .add (' src/index.js') .end () .output .path ('dist') filename (' my-first-webpack.bundle.js'); config.module .rule ('compile') .test (/\ .js $/) .use (' babel') .loader ('babel-loader') module.exports = config
As you can see, webpack-chain can create and modify webpack configurations through the chained function api, which makes it easier to create and modify webpack configurations. Just imagine, what if a webpack configuration needs to be used for multiple projects, but each project has a slightly different configuration?
If you use webpack-chain to modify the configuration, a function api is done, while using imperative programming, you need to step through the entire webpack configuration file to find out the points that need to be modified before you can modify it, which undoubtedly greatly reduces our workload.
The characteristics of functional programming
According to the authoritative definition of Wikipedia, functional programming has the following characteristics:
The function is a first-class citizen
A function can, like a variable, assign a value to another variable, pass in a function as an argument, or return a value as another function.
Use only expressions, not statements:
An expression is a simple operation, and there is always a return value.
Statement is to perform some operation and does not return a value.
In other words, every step in functional programming is a simple operation and has a return value.
No side effects
No results other than operations will be produced.
The same input always gets the same data.
Immutability
Do not modify the variable and return a new value.
Reference transparency
The operation of the function does not depend on external variables, only on the input parameters.
The above features are the core of functional programming. Based on these characteristics, many application scenarios are derived:
Pure function: the same input gets the same output, no side effects.
Function combination: several functions called in turn are combined into one large function, which simplifies the operation steps.
Higher-order function: a function that can be processed to receive one or more functions as input and output.
Closures: function scopes are nested and variables of different scopes are shared.
Corialization: converts a multi-parameter function into multiple nested single-parameter functions.
Partial function: cache some of the parameters and then let others be passed in when they are used.
Lazy evaluation: define multiple operations in advance, but do not evaluate immediately, and evaluate only when values are needed, which can avoid unnecessary evaluation and improve performance.
Recursion: a way to control the circular call of a function.
Tail recursion: optimization to avoid memory overflow caused by multi-level function nesting.
Chained calls: make the code more elegant.
These application scenarios exist in a large number of our daily work, and then we will use a few cases to actual combat.
Common cases of functional programming
Based on the application scenario of functional programming, let's implement several specific cases.
Function combination
Corey
Partial function
Higher order function
Tail recursion
Chain call
1. Function combination, combining multiple function steps.
Function compose (f, g) {return function () {return f.call (this, g.apply (this, arguments));} function toLocaleUpperCase (str) {return str.toLocaleUpperCase ();} function toSigh (str) {return str + "!";} / / combines multiple functions into one function in order of execution, simplifying multiple calling steps. Const composedFn = compose (toSigh, toLocaleUpperCase); console.log ("function combination:", composedFn ("msx")); / / function combination: MSX!
2. Corey, transforming a multi-parameter function into multiple nested single-parameter functions.
/ / function curry (targetfn) {var numOfArgs = targetfn.length; return function fn (... rest) {if (rest.length)
< numOfArgs) { return fn.bind(null, ...rest); } else { return targetfn.apply(null, rest); } }; } // 加法函数 function add(a, b, c, d) { return a + b + c + d; } // 将一个多参数函数转化为多个嵌套的单参数函数 console.log("柯里化:", curry(add)(1)(2)(3)(4)); // 柯里化:10 3、偏函数,缓存一部分参数,然后让另一些参数在使用时传入。 // 偏函数 function isTypeX(type) { return function (obj) { return Object.prototype.toString.call(obj) === `[object ${type}]`; }; } // 缓存一部分参数,然后让另一些参数在使用时传入。 const isObject = isTypeX("Object"); const isNumber = isTypeX("Number"); console.log("偏函数测试:", isObject({ a: 1 }, 123)); // true console.log("偏函数测试:", isNumber(1)); // true 4、惰性求值,预先定义多个操作,但不立即求值,在需要使用值时才去求值,可以避免不必要的求值,提升性能。 // 这里使用 C# 中的 LINQ 来演示 // 假设数据库中有这样一段数据 db.Gems [4,15,20,7,3,13,2,20]; var q = db.Gems .Select(c =>C < 10) .Take (3) / / it will not be evaluated as long as it does not call ToList / / in the specific evaluation, the predefined methods will be optimized and integrated to produce an optimal solution. .ToList ()
In the above code, the traditional evaluation will be traversed twice, the first time traversing the entire array (8 items), filtering out the items less than 10, the output [4jing7d3], the second time traversing the array (4 items), the output [4jing7d3].
If lazy evaluation is used, all predefined operations are judged together, so it only needs to be iterated once. At the same time, it is determined whether the number of less than 10 and the number of less than 10 is 3, and when traversing to item 5, it can output [4 ~ 7 ~ 3].
Compared with the 8-4-12 items traversed by traditional evaluation, only 5 items need to be traversed with lazy evaluation, and the running efficiency of the program is naturally improved.
5. Higher-order functions, functions that can be processed (receive one or more functions as input and output a function).
/ / React component, encapsulates a component as a new component with a default background color. / / styled-components is the principle function withBackgroundRedColor (wrapedComponent) {return class extends Component {render () {return (
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.