Programming Paradigm-Preliminary Exploration of Functional Programming

Introduce

Strategy mode vs functional programming

When introducing Lambda expressions in Java8, from hard coding to strategy mode, and then to the inner class step by step optimization. Theoretically, the functions we use Lambda expressions can also be implemented with strategy patterns and anonymous functions, but why should we introduce Lambda expressions?

What I understand temporarily includes the following aspects:

  1. The code is not easy to read and the structure is complex;
  2. Each additional strategy requires a new implementation class, which is not easy to maintain;
  3. If there are 10,000 situations, do you want to create 10,000 new strategies or anonymous classes?

Functional programming can easily solve the above problems. The advantages and application of functional programming:

  • Easy to refactor, debug and test
  • Overall application: mathematical calculation, artificial intelligence
  • Local application: has blossomed everywhere

concept

——Programming with functions, you need to return to the concept of the function itself:

A function, in mathematics, is a correspondence between two sets: each element in the input value set can correspond to an element in the only output value set. For example , the relationship between the real number x and its square x 2 is a function. If 3 is used as the input value of this function, the resulting output value is 9. --Wikipedia

note:

  • To distinguish the concept from the form of expression The
    function emphasizes a mapping relationship, and the specific implementation can have many ways. For the application side of the function, the specific implementation can be ignored.
  • A function can have different expressions. The expression of the
    square relationship can be: y = x 2 , polynomial expansion, Taylor expansion, etc.

characteristic

Functional programming
No side effects (pure functions): does not modify the state of the program

  • Quote transparent

First class citizen

  • Pass as parameter
  • Return as result
  • Store in data structure

Higher-order functions-can simplify the processing of complex parameters

  • Receive at least one function as a parameter
  • The result is a function

application

  1. Closure: An
    example of a closure in a special function js that references an external scope variable
<script>
var global = "outer"

function outer(){
	var global = "inner";
	var a = 5
	function inner(){
		console.log(global)
		console.log(a++)
	}
	return inner;
}

var r = outer();
r()
</script>
  1. Currying: The technique of modularizing functions and reusing code to transform a multi-parameter function into a series of processes that only accept one parameter
Published 159 original articles · praised 225 · 210,000 views

Guess you like

Origin blog.csdn.net/lyg673770712/article/details/88043237