Functional Programming (1)-how functional programming is implemented

Source: Internet
Author: User

Functional programming is the combination of functions to form a complete program. It is conceivable that the process of function combination can be tortuous, the formation of the program can be complex. So how does functional programming ensure that a complex function combination program is correct? First of all, functional combinations of function programming (functional composition) follow certain mathematical laws (mathematical laws), which ensures that the constituent functions have the required behavioral characteristics (Behavior). Furthermore, all component functions must have a non-changeable behavior, that is, no matter in any situation, it will not affect their behavior because of different final results. If so, the behavior of the composite functions is predictable, and their role in the program can be controlled. What is this non-changeable characteristic explained enough to be around? In fact, this is also the focus of functional programming, I think it should be explained clearly.

A functional program is made up of pure functions. The so-called pure function means that the result of the function is completely or only dependent on its input. For any one input value will only produce a single identical result, and will not be affected by any other cause to become a different result. A function is made up of one or more expressions. An expression that makes up a pure function must be "replaced in equal amounts", meaning that each expression can be substituted for the result of the expression without affecting the behavior of the entire function. I cast aside the literal meaning of the English referencial transparent to translate it into "an equal amount of substitution". We can analyze the understanding function behavior by means of "equal amount substitution". The pure function only relies on the input to produce the result without causing any "collateral impact" (Side Effect). The so-called "collateral effect" is the result of evaluating an expression that affects the function. Because the functional program is composed of pure functions, the pure function is "can be replaced by the same amount", with the behavior of non-changeable characteristics, so it can guarantee the correctness of the functional program.

There is no "collateral effect", but "equal substitution" is the guarantee of the correctness of the functional program, perhaps some examples should be used here to illustrate:

Let's start with a super-simple example: the expression 1+1=2 simple enough. In the Scala language "+" is a function name, we can make sure that the "+" function is a pure function, because we can rest assured that the result and "equal substitution" expression.

Here's a more presentable example:

1 val x = "Hello, world"2 x:java.lang.string = Hello,world3 scala> val r1 = x . Reverse4 r1:string = dlrow, Olleh5 scala> val r2 = x.reverse6 r2:s Tring = Dlrow, Olleh

We try to replace x in R1 and R2 with the result of X, "Hello, World":

1 val r1 = "Hello, World". Reverse2 r1:string = dlrow, Olleh3 scala> val r 2 = "Hello, World". Reverse4 r2:string = Dlrow, Olleh

The values of R1 and R2 have not changed. So we can say that X is an "equal amount of substitution". In fact, R1 and R2 are also "equally replaceable", and when they appear in larger programs, we can also use "isometric substitution" without changing the behavior of the program.

Then one more negative:

1 New StringBuilder ("Hello")2 x:java.lang.stringbuilder = Hello3 scala> val y = X.append (", World")4 y:java.lang.stringbuilder = Hello,World5 scala> val R1 =< c10> y.tostring6 r1:java.lang.String = Hello,World7 scala> val r2 = y.to String8 r2:java.lang.String = Hello, world

When we replace Y with its expression:

1 New StringBuilder ("Hello")2 x:java.lang.stringbuilder = Hello3 scala> val r1 = X.append (", World"). ToString4 r1:java.lang.String = Hello,World5 scala> val R2 = X.append (", World"). ToString6 r2:java.lang.String = Hello, World, world

Obviously, although both R1 and R2 are equal to Y, they replace y with the result x.append (", World") after R1≠R2. This shows that stringbuilder.append is not a pure function, and we must not use it for function composition, because the composition of the program behavior is unpredictable.

From the above example, we can also conclude that the functional program can be understood with normal logic, its role is predictable, not prone to careless errors, can be assured to use.

Think again, the above example stringbuilder.append is not pure function is because StringBuilder is a content can change data structure, is a "can Change" (mutable) data structure. Functional programming requires as much as possible the use of "immutable" (immutable) data structures to guarantee the purity of the program. Functional programming is like a struggle to use the "immutable" data structure process, at least for me.

At the end of this article, let's demonstrate the style of functional programming:

The following example is a familiar OOP style:

1def createerrormessage (errorcode:int): String = {2var result:string = _//declaring a variable3ErrorCode Match {//to re-assign a variable result to a different situation4result = "Network Failure"//Assigning a value to a variable result5       Case2 =6result = "I/o Failure"//Assigning a value to a variable result7       Case_ =8result = "Unknown Error"//Assigning a value to a variable result9    }Ten    returnResult//return Results One}

The above is a typical instruction programming (imperative programming), which changes the state of the program by changing the value of the variable. See examples of functional programming:

1 def createerrormessage (errorcode:int): String = errorCode Match {2case            1 =&G T "Network Failure"3case            2 = "I/o Failure"4Case            _ = " Unknown Error "5 }

First, there is no intermediate variable. The whole function is much simpler and clearer. Returns the result directly without intervening variables, which is a stylistic feature of functional programming.

Functional Programming (1)-how functional programming is implemented

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.