In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly introduces "A brief introduction to javascript functional programming". In daily operation, I believe many people have doubts about the brief introduction of javascript 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 to answer the doubts of "brief introduction to javascript functional programming". Next, please follow the editor to study!
Catalogue
I. introduction
What is functional programming
Pure functions (the cornerstone of functional programming, functions without side effects)
4. Corialization of function
5. Function combination
Declarative and imperative codes
7. Point Free
8. Sample application
I. introduction
Functional programming has a long history, but in recent years it has appeared frequently in the public view. Many languages that do not support functional programming are actively adding closures, anonymous functions and other very typical functional programming features. A large number of front-end frameworks also boast that they use functional programming features, as if once associated with functional programming, it is very high-end, and there are some frameworks and libraries specifically for functional programming, such as: RxJS, cycleJS, ramdaJS, lodashJS, underscoreJS and so on. Functional programming is becoming more and more popular, and mastering this programming paradigm is good for writing high-quality and easy-to-maintain code, so it is necessary for us to master it.
What is functional programming
Wikipedia definition: functional programming (English: functional programming), also known as functional programming, is a programming paradigm that regards computer operations as mathematical functional calculations and avoids the use of program states and volatile objects.
Pure functions (the cornerstone of functional programming, functions without side effects)
In junior high school mathematics, the function f is defined as: for the input x, there is a unique output ytransif (x). This is a pure function. It meets two conditions: 1. This function always produces the same output when it has the same input value. The output of the function is independent of the context state of the current runtime environment. two。 The running process of this function does not affect the running environment, that is, there are no side effects (such as triggering events, initiating http requests, printing / log, etc.). To put it simply, when the output of a function is not affected by the external environment and does not affect the external environment, the function is a pure function, that is, it only pays attention to logical operations and mathematical operations, and the same input always gets the same output. Javascript built-in functions have many pure functions and many non-pure functions.
Pure function: Array.prototype.sliceArray.prototype.mapString.prototype.toUpperCase
Non-pure function: Math.randomDate.nowArray.ptototype.splice
Here we use the slice and splice methods as examples:
Var xs = [1Yue2jinmeng3]; / / Pure xs.slice (0Magne3); / / > [1Yue2Yue3] xs.slice (0Yue3); / / = > [1Yue2Yue3] xs.slice (0JE3); / / = > [1JE2M3] / / impure xs.splice (0JE3); / / = > [1ZHEROMAR3] xs.splice (0Jue 3); / / = > [4Jing 5] xs.splice (0Jing 3); / / = > []
We see that the result returned by the slice method of the array is exactly the same each time, while the xs is not changed, while the return value is different each time the splice method is called, and the xs is changed beyond recognition. This is why we emphasize the use of pure functions, because pure functions have great advantages over impure functions in terms of cacheability, portability, testability and parallel computing. Here we take cacheability as an example:
Var squareNumber = memoize (function (x) {return x;}); squareNumber (4); / / = > 16squareNumber (4); / / read the result with an input value of 4 from the cache / / = > 16
So how do we make a non-pure function pure? For example, the following function:
Var minimum = 21 checkAge = function (age) {return age > = minimum;}
The return value of this function depends on the value of the variable minimum, which depends on the state of the system. In large-scale systems, this dependence on external states is the main reason for the great increase in system complexity.
Var checkAge = function (age) {var minimum = 21; return age > = minimum;}
Through the transformation, we turn checkAge into a pure function, which does not depend on the system state, but minimum is defined by hard coding, which limits the expansibility of the function. We can see how to use functions to solve this problem elegantly in the later Coriarization. So the basic way to make a function pure is not to rely on the system state.
4. Corialization of function
The concept of curry is simple: the process of converting a low-order function into a higher-order function is called Corialization.
To use a figurative analogy is:
For example, for the addition operation: var add = (x, y) = > x + y, we can make it like this:
/ / es5 var add = function (x) {return function (y) {return x + y;};}; / es6 var add = x = > (y = > x + y); / / try var increment = add (1); var addTen = add (10); increment (2); / / 3addTen (2); / / 12
Corialization is of no use for extremely simple functions such as addition. Remember the checkAge function above? We can Corey it like this:
Var checkage = min = > (age = > age > min); var checkage18 = checkage (18); checkage18 (20); / / = > true
This shows that the function Corialization is a kind of "preload" function ability, by passing one or two arguments to call the function, you can get a new function that remembers these parameters. In a sense, this is a cache of parameters and a very efficient way to write functions:
Var curry = require ('lodash'). Curry;// Corienization two pure functions var match = curry ((what, str) = > str.match (what)); var filter = curry ((f, ary) = > ary.filter (f)); / / determine whether there is a space var hasSpaces = match (/\ splasticalg) in the string; hasSpaces ("hello world"); / / [''] hasSpaces ("spaceless"); / / nullvar findSpaces = filter (hasSpaces) FindSpaces (["tori_spelling", "tori amos"]); / / ["tori amos"] V. function combination
Suppose we need to do some column operations on a string, as follows, for example, we only do two operations on a string. We define a new function shout, call toUpperCase first, and then pass the return value to the exclaim function. What's wrong with that? Not elegant, if you do a lot of things, the nested functions will be very deep, and the code is executed from the inside out, not intuitive, we want the code to execute from right to left, and then we have to use combinations.
Var toUpperCase = function (x) {return x.toUpperCase ();}; var exclaim = function (x) {return x +'!;}; var shout = function (x) {return exclaim (toUpperCase (x));}; shout ("send in the clowns"); / / = > "SEND IN THE CLOWNS!"
Using a combination, we can define our shout function as follows:
/ define composevar compose = (... args) = > x = > args.reduceRight ((value, item) = > item (value), x); var toUpperCase = function (x) {return x.toUpperCase ();}; var exclaim = function (x) {return x +'!;}; var shout = compose (exclaim, toUpperCase); shout ("send in the clowns"); / / = > "SEND IN THE CLOWNS!"
The code is executed from right to left, very clear and clear at a glance. Like N-sided glue, the compose we define can combine any number of pure functions together. This flexible combination allows us to combine functional code like building blocks:
Var head = function (x) {return x [0];}; var reverse = reduce (function (acc, x) {return [x] .concat (acc);}, []); var last = compose (head, reverse); last (['jumpkick',' roundhouse', 'uppercut']); / / >' uppercut' VI, declarative and imperative code
Imperative code: command the "machine" how to do things (how), so that no matter what you want (what), it will do as you command. Declarative code: tell the machine what you want (what) and let the machine figure out how to do it (how). Unlike imperative, declarative means that we write expressions, not step-by-step instructions. In SQL, for example, there is no "do this first, then do that" command, there is just an expression indicating what data we want to fetch from the database. It is up to it to decide how to get the data. Whether you upgrade the database or optimize the SQL engine in the future, there is no need to change the query statement at all. This is because there are many ways to parse an expression and get the same result. Here, for ease of understanding, let's look at an example:
/ / imperative var makes = []; for (var I = 0; I < cars.length; iTunes +) {makes.push (cars [I] .make);} / / declarative var makes = cars.map (function (car) {return car.make;})
The imperative loop requires that you instantiate an array and execute the instantiated statement before the interpreter continues to execute the following code. Then directly iterate over the cars list and manually increase the counter, just like you drive a car with all the parts exposed. This is not what an elegant programmer should do. Declarative writing is an expression, and the details of how to iterate through the counter and how the returned array is collected are hidden. It indicates what to do, not how to do it. In addition to being clearer and more concise, the map function can be further optimized independently, even using the extremely fast map function built into the interpreter, so that our main business code does not have to be changed. One of the obvious benefits of functional programming is this declarative code. for pure functions with no side effects, we can focus on writing business code regardless of how it is implemented inside the function. When optimizing your code, you only need to focus on the interior of these stable and robust functions. On the contrary, impure non-functional code can have side effects or rely on an external system environment, and these dirty side effects should always be considered when using them. In complex systems, this is a great burden on the mind of programmers.
7. Point Free
The pointfree pattern means that you never have to say your data. What it means is that the function does not need to mention what the data will look like. The functions of first-class citizens, curry, and combinatorial collaboration are very helpful in implementing this model.
/ / non-pointfree, because data is mentioned: wordvar snakeCase = function (word) {return word.toLowerCase (). Replace (/\ s+/ig,'_');}; / / pointfreevar snakeCase = compose (replace (/\ s+/ig,'_'), toLowerCase)
This style can help us reduce unnecessary naming and keep the code concise and generic. Of course, in order to write the style of Point Free in some functions, it must be less Point Free in other parts of the code, which is a trade-off.
8. Sample application
With the above knowledge, it is time for us to write an example application. Here we use ramda instead of lodash or other class libraries. Ramda provides compose, curry, and many other functions. Our app will do four things:
1. Construct url based on specific search keywords
two。 Send an api request to flickr
3. Convert the returned json into a html image
4. Putting a picture on the screen mentions two impure actions, namely, getting data from flickr's api and placing pictures on the screen. Let's first define these two actions so that we can isolate them. Here we simply wrap the getJSON function of jQuery into a curry function, and change the position of the parameters, and we put them under the Impure namespace to isolate them, so we know that they are all dangerous functions. By using the techniques of function Corialization and function combination, we can create a practical application of function:
Preview address: https://code.h6jun.com/vixe/1/edit?html,js,output look, what a wonderful declarative specification, just say what to do, not say how to do it. Now we can think of each line of code as an equation, and the attribute represented by the variable name is the meaning of the equation.
At this point, the study of "A brief introduction to javascript functional programming" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
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.