Everyone should know something. Functional programming

Source: Internet
Author: User
Tags define function

Directory

    • A problem
    • Functions in functional programming
    • Mathematical and functional programming
    • Mixed-style programming

A problem

Suppose now we need to develop a library of mathematical function plane images (unary) that can provide functions for drawing various function graphs, such as line F (x) =ax+b, parabola f (x) =ax²+bx+c or trigonometric function f (x) =asinx+b and so on. So how to design a public interface? Because the coefficients of each row number (A, B, C, and so on) are different, and the function constructs are different. Under normal circumstances, it is difficult to provide a unified interface. So there is a public method like this:

//drawing a line function image Public voidDrawLine (DoubleADoubleb) {List<PointF> points =NewList<pointf>();  for(Doublex=-Ten; x<=Ten; x=x+0.1) {PointF P=NewPointF (x,a*x+b); Points.    ADD (P); }    //connect the points points together}//draw a parabolic image Public voidDrawparabola (DoubleADoubleBDoublec) {List<PointF> points =NewList<pointf>();  for(Doublex=-Ten; x<=Ten; x=x+0.1) {PointF P=NewPointF (X,a*math.pow (x,2) + B*x +c); Points.    ADD (P); }    //connect the points points together}... DrawLine (3,4);//Draw a lineDrawparabola (1,2,3);//Draw a parabola

If you start with a method like the one above, you need to define n interfaces to draw n different functions. It is obviously impossible to do so.

(Note that if you are using a virtual method, you want to draw n A different function image requires the definition of n classes, each of which needs to be rewritten to generate points 's algorithm)

If we were to think in a different way, since we were drawing images for the function, why would they pass their coefficients as parameters instead of simply passing the function as parameters to the interface? Yes, yes, what function image to draw, then we directly pass the function as an argument to the interface. Because a delegate in C # is a wrapper over a method (function, where the difference between the two is not discussed here), the use of a delegate in C # is as follows:

 Public Delegate DoubleFunction2bedrawed (Doublex);//drawing function Images Public voiddrawfunction (function2bedrawed func) {List<PointF> points =NewList<pointf>();  for(Doublex=-Ten; x<=Ten; x=x+0.1) {PointF P=NewPointF (X,func (x)); Points.    ADD (P); }    //connect the points points together}... function2bedrawed func=( function2bedrawed) ((x)= = {return 3*x +4;});//Create a line functionDrawfunction (func);//draw a line with a coefficient of 3, 4function2bedrawed Func2 =( function2bedrawed) ((x)= = {return 1*math.pow (x,2) +2*x +3;});//Create a parabolic functionDrawfunction (FUNC2);//draw a parabola with a coefficient of 1, 2, 3function2bedrawed func3 =( function2bedrawed) ((x)= = {return 3*math.sin (x) +4;});//Create a sine functionDrawfunction (FUNC3);//a sine function image with a coefficient of 3 and 4 plotted

Above If the function (delegate encapsulation) is passed directly to the interface as a parameter, then the interface can be unified. As for what function to draw exactly, it is entirely up to us to determine it ourselves outside the interface.

It is one of the most important purposes in functional programming to think of a function as a normal type, which can be assigned, stored, passed as a parameter, or even returned as a return value.

Note: In the above code, if you feel that the code to create the delegate object is more complicated, we can define a function to receive a , b two parameters that return a line function, so that the code that creates the delegate does not have to be written repeatedly.

Functions in functional programming

In functional programming, we also treat functions as a type, like other normal types (int,string), where function types can be assigned, stored, passed as arguments, or even as return values of another function. Here is a brief description of C # and F # as an example:

Note: F # is. NET a programming language that focuses on functional programming paradigms in the platform. The code in the example is very simple, and people who have not learned F # can easily read it. F # Getting Started look here: MSDN

Defined:

In C #, we define an integer variable as follows:

int x = 1;

In F #, we define a function as follows:

let func x y = x + y

Assignment value:

In C #, we assign an integer variable to another variable:

int x = 1;
int y = x;

In F #, we can still assign a function to a variable:

Let Func = fun x y-x + y//lambda expression
Let Func2 = Func

Store:

In C #, we can store integer variables in an array:

int[] INTs = new Int[]{1, 2, 3, 4, 5};

In F #, we can still store functions like this:

let func x = x + 1
Let Func2 x = x * x
Let func3 = Fun X-x-1//LAMBDA expression
Let Funcs = [func; func2; func3]//Deposit list, note that the function signature to be stored in the list is consistent

To pass the parameter:

To pass an integer value as an argument to a function in C #:

void func (int a, int b)
{
//
}
Func (1, 2);

Pass a function as an argument to another function in F #:

let func x = x * x//define function func
Let Func2 f x =//define function FUNC2 The first parameter is a function
f x
FUNC2 Func 100//Call Func and 100 as arguments Func2

As the return value:

In C #, a function returns an integral type:

int func (int x)
{
return x + 100;
}
int result = func (1); Result is 101

In F #, one function returns another function:

let func x =
Let Func2 = fun y-X + y
FUNC2//function Func2 as the return value
Let result = (func) 1//result is 101, parentheses can be removed

Math and functional programming

Functional programming is derived from lambda calculus, so it is very similar to the mathematics we have learned. Before we learn functional programming, we'd better forget some of the programming ideas in the previous mind (such as learning C C + +), because the two programming ideas are completely different. The following are examples of some concepts in functional programming and corresponding conceptual relationships in mathematics:

Note: Features of functional programming (features There are many online summaries that can be seen in this blog post.

1. function Definition

In mathematics, the function must have independent variables and dependent variables, so in functional programming, each function must have input parameters and return values. You can see that the functions in F # do not need to be displayed using the keyword return to return a value. Therefore, functions that have no return value for input parameters only, no input parameters for the return value, or both do not exist in pure functional programming.

2. No side effects

The definition of a function in mathematics is: for a definite independent variable, there is only one dependent variable corresponding to it. The implication is that as long as the input does not change, then the output must be fixed. function programming in the function also conforms to the law, the execution of the function does not affect the outside world and will not be affected by the outside, as long as the parameters are not changed, the return value must be unchanged.

3. currying

In functional programming, a function that contains multiple parameters can be converted to multiple functions that contain one parameter. For example, for the following function:

let func x y = x + y
Let result = Func 1 2//result is 3

can be converted into

let func x =
Let Func2 = fun y-X + y
Func2
Let result = (func 1) 2//result result is also 3, you can remove parentheses

As you can see, a function with two parameters is transformed into a function that contains only one parameter, and the function returns another function that receives a parameter. The final call result is unchanged. The advantage of this is that a complex function can be broken down into multiple simple functions, and the function calls can be made step-by.

In fact, in the same vein, there are similar "curry" things in mathematics. When we calculate the function f (x, Y) = x + y, we can first bring x=1 into the function, resulting in f (1,y) = 1 + Y. The result is obviously a function of Y, after which we then bring y=2 into the resulting function, with the result of f (= 1 + 2). The process of this step-down calculation is actually similar to the "curry" in functional programming.

4. immutability

In mathematics we use symbols to denote a value or expression, such as "Make X=1", then x represents 1 and cannot be changed. Similarly, in pure functional programming , there is no concept of "variable", and there is no "assignment" to say that all what we previously called "variables" is an identifier, it is just a symbol, so that it can not be changed after the expression of a thing.

5. Higher- order functions

In functional programming, this type of function, which is called a function, or a return value as a function, is referred to as the "higher order function", as previously mentioned. In mathematics, the process of the derivative function of a function, in fact, is a higher-order function, the original function after the derivation of the transformation of the derivative function, then the original function is the input parameters, the derivative function is the return value.

Mixed-style programming

Programs, object-oriented, and the functions described in this article are all different programming paradigms. Each paradigm has its own dominant programming idea, that is, the way to think about the same problem will be different. It is clear that learning multiple paradigms of programming language has great benefits for our way of thinking.

The computer language of most named "Functional programming languages" is not purely functional, but focuses on "functional" as well as other programming paradigms, whether it is an example of F # or Scala in the Java platform used in this article. Even the once-targeted "object-oriented" C # and Java are now slowly introducing "functional programming Styles". The delegates in C #, anonymous methods, lambda expressions, and so on, all make it possible to do functional programming in C #. If you need to traverse the collection to find the eligible objects, we have done this before:

foreach (person p in list)
{
if (P.age > 25)
{
//...
}
}

Now you can do this:

List. Where (p = = p.age>25). Select (p = p.name). ToArray ();

The questions raised at the beginning of this article are solved by the way of C # delegation, which is essentially a functional idea. Because C # must follow the OO guidelines, introducing delegates helps us to manipulate each function (method) as functional programming.

This article introduces the limited, and does not fully explain the advantages of functional programming, such as its immutable characteristics of non-side effects and other conducive to parallel operation, expression more conducive to human thinking and so on. In fact, the blogger himself has not been involved in the actual use of functional language development projects, but bloggers believe that functional thinking is worth each of us to understand, master. (This article code hand knock not verified, if there is a spelling error forgive)

Everyone should know something. Functional programming

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.