side effects of the function
Transfer from http://www.cnblogs.com/snandy/archive/2011/08/14/2137898.html
A function side effect is when a function is called, in addition to returning a function value, it also has an additional effect on the main calling function. For example, modify global variables (variables outside the function) or modify parameters.
The function side-effects can cause unnecessary trouble to the program design, cause the procedure to be very difficult to find errors, and reduce the readability of the program. Strict functional language requires that the function must have no side-effects.
The function side effects are related to several concepts, Pure function, impure function, referential Transparent.
purely functions (pure function)
The input-output data stream is all explicit (Explicit). Explicit (Explicit) means that functions exchange data with the outside world with only one channel-the parameter and the return value. All input information that the function accepts from outside the function is passed to the inside of the function through parameters. All information that the function outputs to the outside of the function is passed to the outside of the function by the return value.
non-pure functions (impure function)
Contrary to it. Implicit (implicit) means that functions exchange data with the outside world through channels other than parameters and return values. such as reading/modifying global variables, are called as an implicit way to exchange data with the outside world.
reference Transparency (referential Transparent)
The concept of reference transparency is related to the side effects of a function and is affected by it. If two identical expressions in a program can be replaced anywhere in the program without affecting the action of the program, then the program has referential transparency . Its advantage is that it is easier to understand and less obscure than the semantics of non-referential transparent languages. Pure functional languages have no variables, so they all have referential transparency.
The following example illustrates the combination of referential transparency and function side effects?
1 2 3 |
RESULT1 = (Fun (a) + B)/(Fun (a)-C); temp = Fun (a); RESULT2 = (temp + b)/(TEMP-C); |
If the function has no side effects, then RESULT1 and RESULT2 will be equivalent. However, if fun has side effects, such as giving B or C plus 1, then RESULT1 and result2 will not be equal. As a result, side effects violate referential transparency.