Functional programming introduction practice (1)

Before the article, let’s talk about the understanding of Functional Programming, Aka. FP) (here I will use FP refer to function programming):

  1. FP needs The guarantee function is pure, neither relying on the external state variable, nor does it generate side effects. Based on the previous mention, the combination and call of the pure function will not generate dependence on the time order, and the call sequence of multiple functions is not worried that there is a problem, so many potential bugs will also eliminate many potential bugs.
  2. The function must have an input and output. If a function lacks input or output, it is actually a handler Procedure.
  3. The function of the function is as long as possible, if a function has made multiple things, then it should be split into multiple functions.
  4. One of the significance of FP is that in the appropriate timing, the declarative programming is used, and the control and performance of the program stream are abstracted from the perspective of understanding and maintenance.
  5. FP is a paradigm, but does not mean this conflict with OOP (object-oriented programming), both of course can coexist. Personally think that React is actually a good chestnut ~
  6. JavaScript’s functionary citizens and closing features, determined that JavaScript is indeed suitable for displaying FP stage

Closed bag is of course important for JavaScript. However, this is more indispensable for functional programming, the concept that must be mastered, the closure is defined as follows: Closure Is When a Function Remembers and Acces Variables from Outside of Its Own Scope, Even When That Function is Executed in a Different Scope

I believe that most of the students have a good understanding of the closure, but because of the study of FP. Next, I will still take everyone over. The closure is the function of reading other functions


// Closure Demofunction Cube (x) {let z = 1; Return Function Larger (Y) {RETURN X * Y * Z ++;};} const makecube = cube (10); console.log (makecube (5)); // 50console.log (makecube (5)); // 100
  So have you ever thought about the function makecube, or it can be said that the function larger remembers the variable x and z originally not part of its own domain? View makecube.Prototype at the console, and discover that there is a[[Scopes]] CLASURE (Cube) in this built-in attribute to remember the variables X and Z remembered when the function larger returns. If you have multiple layers of functions, you will find multiple closure (names in the Scopes [] array of[[Scopes]] to find variables in order.  
Next, look at the picture test code:


函数式编程入门实践(一) Function Cube (x) {RETURN FUNCTION WRAPPER ( y) {let z = 1; return function larger () {return x * y * z ++;};}} const Makecubey = Cube (10); const makecube= Makecubey (5); Const $ __ var1__ = ‘1. this var is just for test.’; let $ __ var2__ = ‘2. this var is just for test.’; var $ __ var3__ = ‘3. this var is Just For Test. Test. ‘; console.log (makecubey.prototype, makecube.prototype); console.log (Makecube ()); // 50console.log (Makecube ()); // 100

Print Makecubey.Prototype:
  Print Makecube.Prototype:  

through these experiments You can understand JavaScript closure from another angle. How do you find a variable that is not your own domain? Makecube functions found variables Y, Z, Closure in the Closure (Wrapper) in [Scopes]], and found variables x. As for the global let, the constraints of Const declarations are placed in Script, and the global Var declared variables in Global.

Before learning FP, it is especially important to understand the closure ~ Because in fact, a large number of FP tool functions use the closing package. 函数式编程入门实践(一)

函数式编程入门实践(一)

Const unary = fn => arg = > FN (arg);

One yuan function, is applied to simply upload a functionHand a parameter for use. Try to consider the following scenarios:

Console.log ([‘1’, ‘2’, ‘3’]. Map (PARSEINT)); // [1, nan , Nan] Console.log ([‘1’, ‘2’, ‘3’]. Map (unary (paraSeint))))); // [1, 2, 3]

PARSEINT (String, Radix) Receives two parameters, and the callback function called Callback (CURRENTVALUE [, INDEX [, Array]), the second parameter is index, at this time, if Parseint is used Incorrect. Of course, in addition to array.prototype.map, there is more than a parameter in the callback function in a large number of built-in array methods. If there is a scene that only needs the first parameter, the unary function has played its value, no modification function, Elegant and simple access. (For the Unary function, Fn is a variable data of closed bag memory)
   Identity 

const Identity = V => V;
   Have students see the Identity function will feel inexplicable? Why is it? I saw it very confused in the first eye? However, consider the following scenarios: 
Console.log ([False, 1, 2, 0, ‘5’, True] .filter (Identity)); // [1 , 2, “5”, true] console.log ([false, 0] .some); // falseconsole.log ([- 2, 1, ‘3’]. Every (iDentity))); // true

How? On the front of you, I didn’t expect the Identity function to be hidden, in fact, although Identity returned the original value, JavaScript in these functions, the returned value is replaced, which becomes a Boolean value. For example, a Filter function. We can see that MDN definition FILTER describes the following (see whichever).

FILTER () Calls a provided callback function overce for Each Element in ARRAY, AND CONSTRUCTS A New Array Of All The Values ​​for Which Callback Returns a value That coercs to true.

constant
 const constant = v => () => v;   
Similarly, this Function … At first glance, don’t know what to use. However, considering the scenes as follows:

onst p1 = new promise (resolve, reject) => {setTimeout (() => {resolve (‘Hello!’);} , 200);}); p1.Then (() => ‘hi’). Then (console.log); // hi! P1.then (constant (‘hi’)). Then (console.log); // Hi! P1.Then (‘hi’). Then (console.log); // Hello!
   
Because promise.prototype.Then accepts only functions, if I just only need to pass a value, then Constant will provide this convenience. Of course, this does not have any functional improvement, but it is indeed an advantage of readability and a functional programming.

Const spreadargs = fn => argsarr => fn (… argsarr); const gatherargs = Fn => (… argsarr) => fn (argsarr);

Um, these two functions see the name of the name. Among all parameters of a function and collect all parameters, these two functions are obvious, then what their application scenarios is?

SPREADARGS function examples are as follows:
  Function Cube (x, y, z) {RETURN X * Y * z;} function make (FN, POINTS ) {RETURN FN (Points);} console.log (make (Cube, [3, 4, 5])); // nanconsole.log (Make (Spreadargs (Cube), [3, 4, 5])); // 60  
Gatherargs function example is, for example,:

Function CombineFirstTWO ([V1, V2]) {RETURN V1 + v2;} console.log ([1, 2, 3, 4,5] .reduce (combinefirsttwo); // uncaught typeerrorconsole.log ([1, 2, 3, 4, 5] .Reduce (Gatherargs (combinefirstwo))); // 15
   
After reading the above code, the simple two tool functions are easy to make the conversion to a function, so that it applies to another scene. If you should see a little charm of functional programming, then the following two functions will bring more surprises. Partial & Curry

const partial = (fn, … presetargs) => (… laterargs) = > fn (… presetargs, … laterargs); const curry = (fn, arity = fn.length, nextcurried) => (Nextcurried = prevargs => NextRG => {const args = [… prevargs, Nextarg ]; if (args.length> = arity) {Return Fn (… args);} else {return nextcurried (args);}}) (

I believe that everyone should know more or less. Wikipedia definition:
  In computer science, Coriization (English: currying), translated into Carrui or Garyization, is a single parameter (initial) to accept a single parameter (initial) The function of the first parameter of the function, and returns a technique for receiving the remaining parameters and returns the new function of the result. 
Of course, it is benefited from the powerful power of the closure, and Cori is born in the JavaScript world. Please read the code about the Partiel, the CURRY function.
Drink a cup of coffee ~

First simulate an Ajax function as follows:

Function Ajax (URL, PARAMS, CALLBACK) {setTimeout () => {Callback (`Get $ {url} \ nparams: $ {params} \ ndata: hello! $ {params}`);});}
   
Considering Partial Scenes as follows:

Const fetchperson = Partial (Ajax, “http://some.api/person”); Fetchperson (‘Teddy Bear’, Console .log); / * get http: //some.api/person params: Teddy Bear Data: Hello! Teddy Bear * /
 Considering that the use scenario is as follows:   
const fetchperson = curry (ajax) (‘http: //some.api/person’); const fetchunclebarney = fetchperson (‘uncle barney’); FetchuncleBarney (Console. LOG); / * get http://some.api/person paramS: Uncle barney Data: Hello! Uncle barney * /
Partial and Curry function functions, but there are specific different application scenarios, but overall Curry will ratio Partial is more automated.

But! I believe that the classmates who have read the example will have a series of question marks? Why do you have a good parameter for not an incident, not to send such a hassle? The reason is as follows:

The most important reason is that the Partial and Curry functions allow us to separate a function call over time and space by parameter control. Traditional functions require a one-time to make parameters to call, but sometimes we can preset part of the parameters in advance, and incorporate the remaining parameters when this function is finally triggered. At this time, Partial and Curry becomes very useful. The presence of Partial and Curry makes a combination of function combinations. (The function combination is also planned to share with everyone, here is not described later).

Of course, it is most important to improve readability! At the beginning, it may not be so thought, but if you practice the feeling, you may change it.
 P.S. About the practice of functional programming, you can use the Lodash / FP module to introduce the entry practice.   Some thinks 
Because I am also a beginner programming, if you have incorrect place, you are welcome to correct ~
Next, you will continue to organize FP learning materials, learn Practice, serializing some learning and thinking about functional programming, I hope to make progress with you ~

Thank you (● ‘∀ `●) ~

The above is Xiaobian to everyone Introduction to the JavaScript function programming detailed explanation, I hope to help everyone, if you have any questions, please leave a message, Xiaobian will reply to everyone in time. Thank you very much for your support of Tumi Cloud Website!

© Copyright Notice
THE END
Just support it if you like
like0
share
comment Grab the couch

Please log in to comment