Referential transparency
- Input to the same, always get the same output.
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
We can clearly see that for the same input, the second callappend()
and the first callappend()
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:- Modify global variables
- Throw an exception
- IO read and write
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
We can clearly see calling xplusy_v2
time function, changing the value of x, resulting in side effects.
Functional programming advantages
- high productivity
- Ease of reasoning
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) }
。。。