C # functions, delegation, and Lambda expressions for functional programming

Source: Internet
Author: User

I believe many people have heard of functional programming. When talking about functional programming, more languages such as Lisp and Haskell emerge in their minds. C #, it seems that we do not regard it as a functional language. In fact, functional programming is not just for a specific programming language, while C #, it is also step by step to enrich the language structure of the function, to help people better achieve the expected results. Function programming function programming focuses on the application of functions. Function designers use functions as the basic module to create new functions. This does not mean that there are no other languages, function is the main structure for creating a program system. Referential transparency is an important concept in functional programming. The return value of a function that references a transparent function depends only on the value of the parameter passed to it. This is the opposite of the basic idea of instruction program design. In the instruction program design, the state of the program usually affects the return value of the function. The mathematical significance of referencing transparent functions only exists in functional programming. Such functions are called pure functions without side effects. Functional programming is a kind of Oriented Thinking. If we are willing to think in a certain way, it can provide us with interesting solutions or at least the source of thinking, all of which are related to the many practical problems of the current program design. C # It cannot be like Lisp, Haskell, or the same. NET platform F # is so easy to implement functional programming, which we must admit, but from all aspects, using C # To implement functional programming is indeed meaningful. C # function-based functions and methods of functional programming since C # functions can only appear in classes, they are generally called methods. The method can accept several parameters and return a value. Like many object-oriented languages, methods in the C # class can be instance methods or class methods. In pure functional programming, there are no classes and no class instances-of course, there are many ways to save data, but generally they are not used to store data, they are always different in many ways. In an object-oriented environment, all other elements can only appear inside the class and object (the object is another saying of the class instance). In functional programming, all other elements appear in the function. Some data is stored in the local variables of the function and defined in the method as C #, but this is not the best way to save the data. F # Treat a class-level member as a global member. Due to special syntax support, programmers do not need to consider the actual "Conversion" process. Unfortunately, this cannot be implemented in C #, but the solution is the same. To call a global function (or any function with other scopes), You must create a class-level member in the class. These members must use the static keyword. Because they are all encapsulated in the class, the Members in the class have different visibility. Most functional design environments have different encapsulation levels, such as the module level or namespace level. Therefore, apart from some complex syntaxes in C #, there is actually no big difference between the two. Some functional languages use top-level functions or allow the import of modules or namespaces, so that the modifier of function call is not required: 1 DoSomething "string paramers" in C, this call always requires a modifier, that is, the class name, unless this function appears within the same class: 1SomeClass. doSomething ("string paramers"); C # functional programming basis reuse functions in computer programming, reuse is a very important integrated problem. Functions are not the only method that can be reused, especially in Object-Oriented Programming, other methods are emerging soon. As a built-in function of C #, it only supports function overloading as a direct method of function-level modularization. C #4.0 supports named parameters and optional parameters, therefore, the parsing process of the overload function becomes quite complex, especially when it is used together with other related methods (such as generic type inference when the method is called. The following is a simple example of an overload method: 1 int Add (int x, int y) 2 {3 return x + y; 4} 5 6 int Add (int x, int y, int z) 7 {8 return Add (x, y) + z; 9} 10 11 double Add (double x, double y) 12 {13 return x + y; 14} 15 16 double Add (double x, double y, double z) 17 {18 return Add (x, y) + z; 19} in this example, we can clearly see why reload is related to reuse: it allows programmers to create new functions similar to the original function, while making full use of the existing functions of the original function. C # based on functional programming anonymous functions and Lambda expressions not all functions require a name. Generally, these functions are not class-level functions and they have no name, the reference addresses of these functions are stored in the variables, so they can be called as long as there are reference addresses of these functions. Technically speaking, anonymous functions must be subject to certain restrictions. Unfortunately, one of them is that they cannot be generic, nor can they be used to implement iterators. In addition, anonymous functions can include almost all the things that can be done using any "normal" method. 1 static void AnonymousMethods () 2 {3 BubbleSorter. isAGeaterThanBDelegate compareInt = 4 delegate (object a, object B) 5 {6 return (int) a)> (int) B); 7 }; 8} the above is the code of C #2.0. It can be seen that the keyword delegate replaces the method name. The parameter list and method body are the same as those above. This anonymous method can also be rewritten as follows. Here, the Lambda expression syntax of C #3.0 is used: 1 BubbleSorter. isAGeaterThanBDelegate compareInt2 = 2 (object a, object B) =>{ return (int) a)> (int) B) ;}; this code is short, because the delegate keyword is missing, the method body has already been written in a row format. Body => the right side of the operator in a Lambda expression. Several methods can be taken to further simplify the code. First, the parameter type can be omitted, because the compiler can deduce the parameter type based on the declaration statement of the delegate type: View Code. Second, because the function does not perform any operation except to return a value, therefore, you can convert the function body to the expression body and use the implicit return: BubbleSorter. isAGeaterThanBDelegate compareInt2 = (a, B) => (int) a)> (int) B); expression bodies are useful. With it, an operation that would have to be implemented by a function in a functional program can now be simplified to an expression. Like a function, the expression body must accept parameters and return a value. The expression body cannot contain any code irrelevant to the return value (that is, if there is a return value, unfortunately, expressions without return values are often used in the expression body ). In the preceding example, if one of the generic delegation types is used, the format is as follows: 1 Func <object, object, bool> compareInt3 = 2 (a, B) => (int) a)> (int) B); this delegate must accept parameters of the two object types and return a bool value. Another benefit of using generic Delegate types is that their parameter types are easier to understand, because they use explicit declarations in Delegate types, in addition, the compiler can deduce their types for Lambda expressions. When using Lambda expressions, you must note that only when all types are determined will the compiler deduce the types based on several complex criteria. The compiler does not always deduce the type correctly. Therefore, if all types are determined, the compiler's requirements will meet: 1 Func <int, int, int> add = 2 (a, B) => a + B; the var keyword cannot be used in this Lambda expression. in C, the compiler must be able to deduce the parameter type at the declared position. For the following statement, the parameter type cannot be inferred: 1 var add = 2 (a, B) => a + B; functional programming language requirements. explicit descriptions like this are required in all scenarios related to type inference. This is a pity for some C # programmers. C # functional programming basics Extension Method expansion method is a static method represented by a special method in a static class: 1 namespace CompanyWideTools 2 {3 public static class StringHelper 4 {5 public static string ConCat (this string [] strings, string separator) 6 {7 bool first = true; 8 var builder = new StringBuilder (); 9 foreach (var s in strings) 10 {11 if (! First) 12 builder. append (separator); 13 else14 first = false; 15 builder. append (s); 16} 17 return builder. toString (); 18} 19} 20} indicates that Concat is an extension method and uses the this keyword in the parameter list of this method. This keyword is proprietary to C # and is used by the command compiler to add the ExtensionMethodAttribute attribute to this method. You can call an extension method as you call a static method: 1 string [] strings = new [] 2 {3 "to", "be", "or", "not ", "to", "be" 4}; 5 6 Console. writeLine (StringHelper. conCat (strings, ""); however, since it is an extension method, it can also be called as follows: 1 Console. writeLine (strings. conCat (""); this call method is relatively simple when we need to make full use of the advantages of the extension method. Each extension method has a specific extensible type: the type of the first parameter, that is, the parameter marked with this. This flag can be used only for the first parameter, but not for other parameters. The first parameter of the extension method can be a base class type or interface, or even an Object in System. Object. Extension methods can also be generic. They can be extended. C # reference of functional programming basics is transparent in script programming. The basic function of these modules is to prevent code duplication and break down the code into a function-level module that is easier to manage. One of the biggest problems with Script Programming is that modules become larger and larger over time. Because the directive programming focuses on execution sequences, reference to functions and methods is always opaque. Reference transparency: The expression can be replaced by the expression value without affecting the program, that is, the final result of the algorithm using this replacement operation is not affected.

Related Article

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.