Scala learning (9) of the "functional programming"

Referential transparency

  1. Input to the same, always get the same output.
  2. If f (x) and the functions of the parameters x is a reference transparent body, then the function f is a pure function.

    Violate referential transparency examples

    Here Insert Picture Description
    We can clearly see that for the same input, the second call append()and the first call append()when the output is different.

    Pure function (purely sexual function)

    Means that no side effects of function

    side effect

    It refers to the change of state:
  3. Modify global variables
  4. Throw an exception
  5. IO read and write
  6. Call functions with side effects

Examples of side effects

var x = 1
def xpulsy_v1(y: Int) = x + y
def xpulsy_v2(y: Int) = {x += y; x}

x
xpulsy_v1(2)
x

xpulsy_v2(2)
x

Here Insert Picture Description
We can clearly see calling xplusy_v2time function, changing the value of x, resulting in side effects.

Functional programming advantages

  1. high productivity
  2. Ease of reasoning
  3. Parallel Programming

    The function assigned to the variable

    Scala's syntax specified when the function assigned to the variable, must be added after the function spaces and underscore

def sayHello(name: String) { println("Hello, " + name) }

。。。

Scan code to view the message history, to get the complete version of the article

Here Insert Picture Description

Guess you like

Origin www.cnblogs.com/Alex458/p/12319233.html