Functional Programming Literacy Chapter

Source: Internet
Author: User
Tags mathematical functions what magic

In the past decade or so, object-oriented programming has been a big line. So that in college education, teachers will only teach us two programming models, process-oriented and object-oriented.

It is not known that, before object-oriented generation, functional programming has been around for decades before object-oriented thinking is produced.

So, then, let's review this ancient and modern programming model, and let's see what magic is going to bring this concept to our perspective again in 21st century today.

2. What is functional programming

In Wikipedia, functional programming has been introduced in great detail.

So let's take a look at the definition of functional programming on the wiki:

In computer science, functional programming are a programming paradigm that treats computation as the evaluation O f mathematical functions and avoids state and mutable data.

A simple translation, that is, functional programming is a programming model, he regards computer operations as mathematical functions in the calculation, and avoids the concept of state and variable .

Next, we will analyze some of the features of functional programming.

3. Speaking from concurrency

I'm ashamed to say that my first real contact with functional programming goes back to the two-year-old Erlang program, and we know that Erlang is a functional programming language that supports high concurrency with strong fault tolerance.

Because the time is too long, and has not been really applied, so to Erlang also just stay in some perceptual knowledge. In my eyes, Erlang supports high concurrency in two ways, first,Erlang's support for lightweight processes (note that the process here is not equal to the operating system, but just one unit unit inside Erlang), and the second is the invariant .

4. Invariance of variables

In the book "Erlang Programming", the invariance of variables is said, Erlang is the only variable invariant language. I do not remember the specific words, I do not know is that the Don is written, or the translator's problem. When I was writing a book review, I said with fault:

I have an objection to this sentence, do not say that once lisp, and then to today's F # are on the assignment of value operation, inferior. In today's Java and C #, the provision of final and readonly can support variable invariance, which is a bit too aloof.

Let's take a look at the two programs, first of all we have a common program that contains assignments:

Class Account:
def __init__ (self,balance):
Self.balance = Balance
def desposit (Self,amount):
Self.balance = self.balance + Amount
Return self.balance
def desposittwice (self):
Self.balance = self.balance * 2
Return self.balance

if __name__ = = ' __main__ ':
Account = Account (100)
Print (Account.desposit (10))
Print (Account.desposittwice ())

This procedure itself is not a problem, but we consider a situation, now there are multiple processes at the same time running this program, then the program will be first desposit or first desposittwice influence.

But if we take this approach:

def makeaccount (balance):
Global Desposit
Global Desposittwice
def desposit (amount):
result = Balance + amount
return result
Def desposittwice ():
result = Balance * 2
return result
Def dispatch (method):
Return eval (method)
Return Dispatch

if __name__ = = ' __main__ ':
Handler = Makeaccount (100)
Print (Handler (' Desposit ') (10))
Print (Handler (' Desposittwice ') ())

At this point we will find that no matter how many processes are running, because we do not have an assignment operation, it will not affect our final result.

But as you can see, there is no way to keep the state in this way.

This is what we see in the previous concept of statelessness.

5. Look again at the rise of functional programming

Now that we have seen the basic features of functional programming, let's consider the reasons behind the resurgence of functional programming decades later.

For a long time, Lisp, or Haskell, represented as functional programming, is more often used in universities, in labs, and rarely in real production environments.

First let's review the Great Moore's Law:

1, integrated circuit chip on the number of circuits, every 18 months to double.

2, the performance of the microprocessor is increased by one times every 18 months, and the price is reduced by half.

3, the use of a dollar can buy computer performance, every 18 months to double.

As Moore predicts, the entire information industry is moving forward in such a rapid way, but in recent years we can find that Moore's law is gradually failing, and that the size of the elements on the chip is not infinitely reduced, which means that the number of electronic components that can be integrated on the chip is bound to reach a limit at some point. So when the technology reaches this limit, how can we adapt to the increasing demand of computing, the electronics manufacturers give the answer, is multicore.

Multi- core parallel programming is pushed to the front, and the inherent flaw of imperative programming makes the parallel programming model very complex, whether it is the signal volume, or the concept of lock, which makes the programmer unbearable.

In this way, functional programming finally after decades, finally out of the laboratory, came to the real production environment, whether it is the haskell,erlang of the unpopular, or scala,f#, are functional programming success is typical.

6. The first type of functional programming

We know that object is the first type of object-oriented, then functional programming is the same, the function is the first type of functional programming.

We try to use functions to express all the concepts in functional programming and do all the work.

In object-oriented programming, we transmit the object, that in functional programming, we have to do is to pass the function, and this, as a term, we call him the higher-order function .

Then we will look at a high-order function of the application, familiar with JS students should be familiar with the following code, let oh we write a filter in the electronic circuit commonly used in the sample code.

def Filt (Arr,func):
result = []
For item in ARR:
Result.append (func (item))
return result

def myfilter (ele):
If Ele < 0:
return 0
Return ele

if __name__ = = ' __main__ ':
arr = [ -5,3,5,11,-45,32]
Print ('%s '% (Filt (arr,myfilter)))

Oh, I forgot to say, what is called the higher order function, we give the definition:

In mathematics and computer science, higher-order functions are functions that meet at least one of the following conditions:

  • Accept one or more functions as input
  • Output a function

Well, there is no doubt that the above filter is an application of higher-order functions.

In functional programming, the function is the basic unit, the first type, and he is almost used for everything, including the simplest calculations, and even the even variables are replaced by calculations. In functional programming, a variable is simply a name, not a storage unit, which is the most typical difference between functional programming and traditional imperative programming.

Let's see, the variable is just a name, in the code above, we can rewrite the main function like this:

if __name__ = = ' __main__ ':
arr = [ -5,3,5,11,-45,32]
Func = Myfilter
Print ('%s '% (Filt (arr,func)))

Of course, we can also streamline the program by using the tool in functional programming, map,filter and reduce:

if __name__ = = ' __main__ ':
arr = [ -5,3,5,11,-45,32]
Print ('%s '% (map (lambda x:0 if x<0 else x, arr))

Does it look more pleasing to the eye?

So we can see that the function is the basic unit of our programming.

7. Mathematical nature of functional programming

Forget who said: all problems, in the final analysis, are mathematical problems.

Programming has never been difficult, nothing more than careful, coupled with a number of functional library familiarity, coupled with the accumulation of experience, and really difficult, is how to put a practical problem, the transformation into a mathematical model. That's why companies such as Microsoft and Google value algorithms, which is why mathematical modeling contests are so valued in college computer systems.

Assuming that we have established mathematical models with our good mathematical thinking and logical thinking, the next thing to do is to express the mathematical language as a programming language that the computer can read.

Here we look at the fourth section, we mention the assignment model, the same function, the same parameter, but in different scenarios to calculate the different results, which is completely impossible in the mathematical function of the case,f (x) = y, then this function in whatever scenario, the same result will be obtained, This certainty that we call function.

This is also where the assignment model is incompatible with the mathematical model. and the function programming cancels the assignment model, then makes the mathematical model and the programming model perfect unification .

8. Abstract nature of functional programming

I believe that every programmer is not unfamiliar with the concept of abstraction.

In object-oriented programming, we say that a class is an abstract representation of a real thing. So the greatest role of abstraction in my opinion is the reuse of abstract things , the more specific things, then his reusability is lower, therefore, we re-build reusable code, class, class library, in fact, the essence of the work is to improve the abstraction of the code. And then the big one, the Programmer's job is to abstract a series of processes, reflected as a common process , and then expressed in code.

In object-oriented, we abstract things. In functional programming, we are in the abstract of the function method, the sixth section of the filter has let us know that functions are reusable, can be replaced by the abstract units.

Then we say that the abstract nature of functional programming is to use functions as an abstract unit, and as a form of code, higher-order functions .

9. What's the status?

We said a lot of features of functional programming, but we ignore, these are on the ideal level, we look back to the fourth section of the variable invariance, indeed, we say that functional programming is stateless, but in our reality, the state can not always remain unchanged, and the state must change, pass, So, in functional programming, we save it in the parameters of the function and pass it as an accessory to the function.

PS: In Erlang, the interaction between processes is passed through the "mailbox" to send and receive letters to achieve, in fact, we think about, in essence, is also the variable as an accessory to pass it!

Let's take a look at an example where we're going to give an example of X's N-square, and we'll write it in traditional imperative programming:

def expr (x,n):
result = 1
For I in Range (1,n+1):
result = result * x
return result

if __name__ = = ' __main__ ':
Print (expr (2,5))

Here, we have been assigning a value to the result variable, but we know that the variable in the functional programming is invariant, so we need to pass result as a function parameter to maintain the state in order to maintain the result state:

def expr (num,n):
If n==0:
Return 1
Return num*expr (num,n-1)

if __name__ = = ' __main__ ':
Print (expr (2,5))

Yo, this is not recursion!

10. Functional Programming and recursion

Recursion is an important concept of functional programming, and loops can be no, but recursion is indispensable for functional programming.

Here, I have to admit, I really don't know how I can explain why recursion is so important to functional programming. All I can think of is that recursion fully exerts the power of the function and solves the problem of functional programming without state. (If you have other comments, please enlighten us)

Recursion, in fact, is to decompose the big problem indefinitely until the problem is small enough.

The biggest difference between recursion and loop in programming models and thinking models is that:

The loop is describing how we are going to solve the problem.

Recursion is the definition that describes the problem.

So let's take the Fibonacci sequence as an example and look at both of these programming models.

First of all, let's say our most common recursive model, where I don't use dynamic planning to do a temporary state of caching, just say this idea:

Def Fib (a):
If A==0 or a==1:
Return 1
Else
Return Fib (a-2) +fib (A-1)

Recursion is describing what a Fibonacci sequence is, and the definition of this sequence is that a number equals his first two entries, and that the FIB (0) and FIB (1) are known to be equal to 1. The program uses computer language to describe the definition again.

So next, let's look at the Loop model:

def Fib (n):
A=1
B=1
n = n-1
While n>0:
Temp=a
A=a+b
B=temp
n = n-1
Return b

Here is a description of how we can solve the Fibonacci sequence, and what we should do first.

And we can clearly see that recursion is more readable than looping.

However, we can not ignore, recursive and produce the StackOverflow, and the assignment model? We understand that functional programming cannot be assigned, so what should I do?

11. Tail recursion, pseudo recursion

Before we talked about recursion and the problem of loops, how to solve this problem, functional programming throws us the answer, tail recursion.

What is the tail recursion, in the most popular words: is in the last simple to call the recursive function , here we should pay attention to the word "simple".

Then we say the tail recursion principle, in fact, the tail recursion is not to keep the current recursive function state, and the need to keep everything with parameters to the next function, so you can automatically empty the stack space of this call. in this case, the stack space occupied is the constant order.

Before looking at the recursive code, we should first clarify the classification of recursion, we will recursively divided into "tree-shaped recursion" and "tail recursion", what is the tree-shaped recursion, is the calculation process to expand, and finally formed a tree-like structure , such as the previous Fibonacci sequence recursive solution.

So let's look at the recursive notation of Fibonacci endings:

def Fib (a,b,n):
If n==0:
Return b
Else
Return Fib (b,a+b,n-1)

It seems a bit difficult to understand here, let's explain: the incoming A and B are the first two numbers, then every time I push one, then B becomes the first number, and A+b becomes the second number.

This is the tail recursion. In fact, we think that this is not to describe the problem, but to find a solution to the problem, and what is the difference between the above cycle? Let's do a transition from tail to loop!

Last return b Yes, I'll just declare it, b=0.

To pass in a is to put, I also declare, a=1

To calculate whether the n==0 is a turn, or a loop while n!=0

Every time I do a calculation like that, I'll swap it with a temporary variable. Temp=b; B=a+b;a=temp.

Then follow this idea step by step, is it the loop code we wrote on it?

so this tail recursion, in essence, is a "pseudo-recursive", you say?

Since we can optimize, for most functional programming language compilers, they also provide an optimization for the tail recursion, so that the tail recursion can be optimized in the form of loop iterations so that it does not cause a stack overflow situation.

12. Lazy Evaluation and parallelism

The first contact to the lazy evaluation concept should be in the Haskell language, looking at the simplest lazy evaluation, I think is also the most classic example:

In Haskell, there is a repeat keyword whose role is to return an infinitely long list, so let's look at:

Take ten (repeat 1)

This is the code, if there is no lazy evaluation, I think this process will die there, but the result is very normal, returned to the length of 10 of the List,list value is 1. This is a typical case of lazy evaluation.

Let's look at a simple code like this:

Def getresult ():
A = Geta ()//take a long time
b = Getb ()//take a long time
c = A + b

The code itself is very simple, in imperative programming, the compiler (or interpreter) will do is to explain the code one by one, in order to find the values of A and B, and then find C.

However, we consider from a parallel point of view, is the value of a can be parallel to the value of B? That is, until we execute to a+b, our compiler realizes that A and B are only needed until now, so our dual-core processor naturally goes to the maximum efficiency to calculate it!

This is the maximum power of lazy evaluation.

Of course, the lazy evaluation has such advantages and must have shortcomings, I remember I have seen an example is the most classic:

Def Test ():
Print (' Please enter a number: ')
A = Raw_input ()

But if the code is lazy, the first sentence is not necessarily executed before the second sentence.

13. Functional Programming Overview

After reading the features of functional programming, we think about the application of functional programming.

1. Mathematical reasoning

2. Parallel programs

Then we generally say, in fact, functional programming is the most suitable to solve the small problem of local mathematics, to let functional programming to do crud, to do our traditional logic is very strong web programming, some are not difficult for it.

Just like if you're going to use Scala to completely replace the work of today's Java, I'm afraid it's going to be a bad effect. It would be appropriate for Scala to be responsible for the preparation of the underlying services.

And in a language to incorporate the multiple language paradigm, the most typical C #. With the introduction of lambda expressions in C # 3.0 and the introduction of declarative programming in C # 4.0, some of us laughed at the growing popularity of C # while ignoring the syntax sugar that brought us more than just a traversal of code writing, but more importantly a progression of programming thinking.

Well, let's forget about the implementation mechanism behind Lambda in C #, in C #, or in languages that support more purely functional programming, to experience the joy of functional programming!

[Turn] http://www.cnblogs.com/kym/archive/2011/03/07/1976519.html

Functional Programming Literacy Chapter

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.