Development Trend and future direction of programming language (3): Functional Programming

Source: Internet
Author: User

See http://blog.zhaojie.me/2010/05/trends-and-future-directions-in-programming-languages-by-anders-3-functional-programming-and-fsharp.html

This is the opening speech by Anders hejlsberg at techdays 2010, Belgium. Since I have discussed many languages in my blog recently, I plan to write the Anders speech in full out of context. In the previous section, Anders elaborated on the concept and DSL of Declarative Programming in his eyes, and demonstrated an internal DSL form in C #: LINQ. In this section, Anders talked about another important component of Declarative Programming: functional programming, and demonstrated it using functional programming language F # On the. NET platform.

Unless otherwise stated, all texts are directly translated from Anders speeches and expressed using my own oral habits, if necessary, the translation will be ignored. For ease of understanding, I will also take key parts in the video, and some code demos will be published directly as the content of the article.

(Start with dictation. Next part)

 

Another important part of Declarative Programming is functional programming. Functional programming has been around for a long time, and lisp was a functional programming language. Apart from lisp, we also have many other functional programming languages, such as APL, Haskell, scheme, and ML. Functional programming has had a lot of research in the academic world, and about five to ten years ago many people began to absorb and sort out the research content and want to integrate them into a more general programming language. Today's programming languages, such as C #, Python, Ruby, and Scala, are all affected by functional programming languages.

 

I would like to take a few minutes to briefly introduce the functional programming language in my eyes. I have found many people have heard of functional programming languages, but they are not quite clear about the differences between them and common imperative programming languages. Today, when we use imperative programming languages to write programs, we often write such statements. Hi, X is equal to x plus one. At this time, we rely heavily on States, variable states, or variables, their values can change as the program runs.

The variable state is very powerful, but the problem that comes with it is called "Side effects. When you use a mutable state, your program contains side effects. For example, you can write a void method without parameters, then it will affect the program based on the number of calls or on which thread, because the void method will change the internal state of the program, thus affecting the subsequent running effect.

This is not the case in functional programming, because all States are immutable. You can declare a state, but it cannot be changed. And because you cannot change it, you do not need variables in functional programming. In fact, the discussion of functional programming is more like mathematics and formulas than program statements. If you give the sentence "x = x + 1" to a programmer, he will say "ah, you are adding the value of X". If you give it to a mathematician, he would say, "Well, I know this is not true ".

 

However, if you show him the language, he will say, "Ah, Y is equal to x plus one, that is, to give the computing result of x + 1 to y, you specified a name for this calculation ". At this time, thinking is another way. Here y is not a variable, it is just the name of x + 1, it will not change, it always represents x + 1.

So in functional programming languages, when you write a function and accept some parameters, when you call this function, only the parameters you pass in will affect function calling, all you get is the calculation result. In a pure functional programming language, a function does not make some magical changes during computing. It only uses the parameters you give it, and then returns the results. In functional programming languages, a void method is meaningless. Its only function is to heat up your CPU, without giving you anything or any side effects. Of course, now you may say that the CPU usage is also a side effect. Okay, but we will not discuss this issue now.

 

The key here is that your solution is different from the previous one. Here I still use code to illustrate the problem. Using Functional Languages to write code without any side effects is like using final or readonly members in Java or C.

For example, here we have a point class. The constructor accepts X and Y. There is also a moveBy method that can move a point to some locations. In traditional imperative programming, we will change the status of the Point instance, which may not be a problem during normal times. However, if I submit a point object to three APIs at the same time and then modify the point object, how can I tell them that the status has changed? Maybe we can use events, blablabla. If we don't have any events, we will have unpleasant side effects.

If you use functional programming to write code, your point class can still contain states, such as X and Y. However, they are readonly and cannot be changed after initialization. The moveBy method cannot change the point object. It can only create a new point object and return it. This is a function for creating a new point object, isn't it? In this way, the caller can decide whether to use the new or old point object, but there will be no side effects.

In function programming, point objects are not only allowed. For example, we have collections, such as Dictionary, map, and list. They are all immutable. In functional programming, when we add an element to a list, we will get a new list that contains new elements, but the previous list still exists. Therefore, the implementation of these data structures is fundamentally different. their internal structures will try to make such operations as efficient as possible.

In function programming, the access status is safe because the status will not change. I can give a point or list object to any number of places for access without worrying about any side effects. Function programming is very easy to run in parallel, because I do not modify the status at runtime, so no matter how many threads are running, you can observe the correct status. The two functions are completely irrelevant, so there is no difference between parallel or sequential execution. We can also have latency computing and memorization, which are very interesting aspects in functional programming.

You may say, why don't we use this method to write programs? Well, in the end, as I said before, we can't just let the CPU heat up, but we must present the computing results. When we print the content on the screen, or write the data into a file or socket, it actually produces side effects. Therefore, functional programming in the real world often isolates pure parts or implements more detailed control. In fact, there will not be really pure functional programming languages, they will bring some side effects or the ability of imperative programming. However, they are functional by default. For example, in functional programming languages, everything is immutable by default, you must do additional things to use a mutable state or cause dangerous side effects. At this time, your programming concepts will be different.

 

We developed such a functional programming language in our own environment, F #, which is already included in vs 2010. F # was born at the Cambridge Research Institute of Microsoft. It was proposed by Don Syme that he has been working on F # for 5 to 10 years. F # uses a common core component of ocaml, another functional programming language. Therefore, it is a strong type language and supports Features of Modern functional programming languages such as pattern matching and type inference. In addition, F # adds more advanced language functions such as Asynchronous workflows and measurement units.

And f #, the most important thing is, in my opinion, it is the first and industrial framework and tool set, such. net and Visual Studio, with a deeply integrated functional programming language. F # allows you to use the entire. NET Framework. It and C # also have similar execution period features, such as strong types and generate efficient code. I think it is time to show some F # code.

 

First, I want to start with my favorite feature in F #. This is an F # command line ...... (Open the command line window and a f # source file )...... F # contains an interactive command line, which allows you to directly input and execute the code. For example, enter 5 ...... X equals to 5 ...... Then X ...... The value of X is 5. Then let sqr X be equal to X multiplied by X, So I defined a simple function named sqr here. So we can calculate that sqr 5 is equal to 25, and sqr 10 is equal to 100.

F # is very dynamic, but in fact it is a strong type of programming language. Let's take a look. Here I define a function sumsquares for calculating the sum of squares. it traverses each element in each list and then adds them together. Let me write this function in the imperative way, and then in the functional way, you can see the difference.

let sumSquaresI l =     let mutable acc = 0    for x in l do        acc <- acc + sqr x    acc

Here is the imperative code. First, we create a accumulators ACC with 0, traverse the list l, add the square to ACC, and then return ACC. There are several things worth noting. First, to create a mutable state, I must explicitly declare it using mutable, Which is immutable by default.

 

Another point is that I did not provide any type information in this Code. When I move the mouse over the method, it will show that the sumsquaresi method accepts an int sequence as a parameter and returns an int. You may wonder where int comes from. Well, it is inferred from the type. The compiler finds from 0 that ACC must be an int, so it finds that the plus sign indicates the addition of the two int, so the sqr function returns an int, and then blablabla ...... Eventually, it finds that int is everywhere.

 

If I change the value to floating point 0.0, move the cursor over and you will find that the function accepts and returns the float type. Therefore, the type inference function is very powerful and convenient.

 

Now I can select this function to execute it in the command line, and then call sumsquaresi to provide a sequence of 1 to 100.

let rec sumSquaresF l =     match l with    | [] -> 0    | h :: t -> sqr h + sumSquaresF t

Now let's change to a functional style. Here is another way of writing. It can be said that it is a pure function implementation method. If you understand this code, you will find a lot of mathematical feelings. Here I define the sumsqauresf function, enter an L list, and then use the following pattern to match l. If it is null, the result is 0. Otherwise, the list is matched to the header and tail, and the sum of the squares at the end of the header is added.

You will find that during calculation, I will not change the value of any variable. I just create a new value. Here I will use recursion, just as we often use recursion in mathematics. We break down a formula into several forms of change for Recursive definition. We also use recursion in programming, and then the compiler will try to convert it into tail recursion or loop.

So we can execute the sumsquaresf function and get the same result. Of course, you may not write code as before, and you may use higher-order functions:

let sumSquares l = Seq.sum (Seq.map (fun x -> x * x) l )

For example, here, I just map the Function x by X to the list and then add it together. In this way, the same results can be obtained, and this may be a more typical practice. I just want to explain that this language may bring you a completely different feeling during programming, although its execution period features are similar to that of C.

This is about F.

(To be continued)

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.