Functional programming ideas

Source: Internet
Author: User

-1. Introduction to functional programming background functional programming was born more than 50 years ago. More and more people begin to accept and implement functional programming practices. Not only is the oldest functional Language Lisp young, but new functional languages are emerging, such as Erlang, clojure, Scala, and F. Currently, the most popular Objective-C, Python, Ruby, and Javascript have introduced support for functional programming. Even the old Object-Oriented Java, process-oriented PHP, and Apple's latest swift language are busy adding anonymous functions and other mechanisms. There are more and more signs that functional programming is no longer a favorite in the academic world and has begun to be practical in the industry. Also, after object-oriented programming, functional programming will become the mainstream paradigm of the next programming. When talking about functional programming, We Have To Say object-oriented. Object-oriented is to encapsulate a group of operations and related data of a function in an object. Object-oriented is the object that is everywhere. Function programming encapsulates an operation of a function and related data. Function programming is a function that is everywhere. Functional programming has a smaller granularity and shorter lifecycle than object-oriented programming. The effective way to reduce bugs is to reduce the lifecycle of variables and reduce the granularity of modules. Therefore, functional programming is not easy to introduce bugs. Definition is a programming paradigm that treats computer operations as mathematical function calculations and avoids the use of Program states and variable objects. Lambda calculus is the most important foundation of function programming languages ). The most critical element in the lambda algorithm is that the function is processed as a variable and can be involved in the operation. Value-based functional programming emphasizes that the execution result of a program is more important than the execution process. Focus on the problem of description, rather than how to implement and hide the implementation details. To simplify. Using a number of simple execution units, the computing results are gradually produced, and complex operations are derived layer by layer. -Your Excellence has nothing to do with my life. Please take your arrogance. The following is an example of the output array shoplist = ['apple', 'mango ', 'carrot', 'Banana'] print 'my shopping list is now ', shoplist # output # My shopping list is now ['banana ', 'carrot', 'mango', 'Rice']. This code is easier to read and only describes what it is, instead of how to implement this. For procedural programming, a for loop is required to describe the implementation details. Function programming Splits a problem into several subproblems to solve complex computing problems. Software or program Assembly becomes simpler and more intuitive. This makes the code easier to understand, facilitate troubleshooting, and provide better maintainability and scalability. Now there is such a mathematical expression: (1 + 2) * 3-4 traditional procedural programming: var a = 1 + 2; var B = a * 3; var c = B-4; functional programming requires the use of functions. We can define the calculation process as different functions and then write them as follows: var result = subtract (multiply (add (1, 2), 3), 4); Your Excellence has nothing to do with my life. Please take your arrogance. This is the functional programming principle: the function is not affected by external variables, does not depend on external variables, and does not change the value of external variables. Traditional procedural programming: int count; void increment () {returen count ++;} functional programming: def increment (count): return count + 1; the function does not access or change global variables. 2. Functional Programming feature encapsulation, inheritance, and polymorphism are three main features of object-oriented programming. Function programming also has its own language features. Immutable data (immutable data) many variables can only be assigned once, the variable is unchangeable, if you want to change the variable to create a new variable. The immutability of data ensures that the program is stateless, and many difficult bugs are often caused by various complex states. For example, if you find that the program runs properly in some situations, it is caused by a certain State. However, there are 100 possibilities for this state, and operations are performed in 1000 places. The idea of killing people in debug is lost. Data immutability also ensures that the function has no "Side effects". The side effects of the function mean that in addition to returning the function value, the function is also called for the main function-the function is the first class method) functions can be used like common variables. A function can be created, modified, passed as a variable, returned, or nested in a function. -Referential transparency indicates that the function runs independently of external variables or "States" and only depends on the input parameters. If the parameters are the same at any time, the returned values obtained by calling a function are always the same. It is natural to adapt to concurrent programming, because the results of calling functions are consistent, so there is no need to lock, there is no deadlock problem. -Tail call optimization: Because function calls require stack pressure to be stored on the site, too many stacks may cause performance problems if the recursive hierarchy is too deep. Therefore, tail recursion optimization is introduced to improve performance by reusing stacks each time a recursion occurs. Example of passing a function as a parameter NSComparisonResult (^ cmp) (id obj1, id obj2) = ^ NSComparisonResult (id obj1, id obj2) {return [obj1 is1_tostring: obj2];} NSArray * items = [@ "a", @ "c", @ "d"]; [items sortedArrayUsingComparator: cmp]; sortedArrayUsingComparator method is responsible for sorting, you need to tell the comparison rule to pass the comparison method as a parameter to the function for calculation. -3. Functional Programming (methodology)-map and reduce function programming the most common technology is to Map and Reduce a set. This is easier to read in code than in procedural languages. The traditional procedural language needs to use a for/while loop, and then put a group of functions in an array or list in various variables in the Data inverted-pipeline (pipeline, then, pass the data to this list, and the data is operated by each function in the same order as a pipeline to get the desired result. His philosophy is to make every function do one thing, and to make it the ultimate, the assembly of software or programs will become more simple and intuitive. -The biggest benefit of recursive (recursing) is to simplify the code, which can describe a complicated problem with simple code. The essence of recursion is the problem of description, which is the essence of functional programming. -Currying splits multiple parameters of a function into multiple functions and encapsulates them in multiple layers. Each layer of functions returns a function to receive the next parameter. -When a high-order function is a parameter, it encapsulates the passed functions and returns the encapsulated functions. The function transmits the Python code of map & reduce: def toUpper (item) return item. upper () print map (tuUpper, ["hellow", "world"]) converts all strings in the array into uppercase and uses map directly without writing for loops. Output ["HELLO", "WORLD"] print reduce (lambda x, y: x + y, [, 5]) to accumulate all the values in the array, equivalent to 1 + 2 + 3 + 4 + 5, output 15. Lambda is an anonymous function of Python. lambda x, y: x + y is equivalent to def func (x, y ): return x + y pipeline if there is a requirement to find all the even numbers in a group and calculate the square of them, and finally calculate their sum, it can be divided into three steps: 1) Find the even number 2) square 3) accumulate and copy the code def even (nums): return filter (lambda x: x % 2 = 0, nums) def square (nums): return map (lambda x: x * x, nums) def total (nums): return reduce (lambda x, y: x + y, nums) nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] pipeline = total (square (even (nums) copy the Code even method to calculate the number of even, square to calculate their square, and the total method to add them together. Concatenate them through pipelines to complete a complicated process. Let every method do only one thing and make it the best. Recursion in other types of languages, variables are often used to save the state. The variable is unchangeable, meaning that the State cannot be saved in the variable. Function programming uses parameters to save the state. The best example is recursion. Copy the code void fun (const int I) {if (I <10 & I> = 0) {NSLog (@ "I: % d", I ); fun (I + 1) ;}} each time the Code status changes, the value is + 1. Curialization and higher-order functions are just one function with only one parameter. What if two parameters are required, such as the sum and summation of two numbers. It is implemented by encapsulating a parameter into a function. Copy the code def func (a): def add (B): return a + B return add funcA = func (5) print funcA (10) copy the code func function and return an add function, the funcA variable is an add function with a value of 5. Print funcA (10) is to input 10 to the add function. The final result is 5 + 10 and the output is 15. -4. Functional Programming significance 1. The code is concise, and function programming is developed quickly to use a large number of functions, reducing code duplication. Therefore, the program is short and the development speed is fast. 2. Similar to natural language, it is easier to understand what functional programming focuses on rather than how to do it. 3. Convenient Code Management and Maintenance function-based programming does not depend on and does not change the external State. As long as the input parameter is specified, the returned results must be the same. Therefore, each function can be considered as an independent unit, which is conducive to unit testing, debugging, and modular combination. 4. Easy concurrent function programming because it does not modify variables, there is no "Lock" thread problem at all, and you do not need to consider "deadlock" (deadlock ). You don't have to worry about the data of one thread, which is modified by another thread. Therefore, you can share your work with multiple threads with confidence. -5. Code hot upgrade function programming has no side effects. As long as the interface remains unchanged, internal implementation is external. Therefore, you can upgrade the Code directly in the running state without restarting or stopping the instance. Erlang has long proved this point. It was developed by Ericsson in Sweden to manage the telephone system. Of course, the upgrade of the telephone system cannot be stopped. Finally, it is not important to use object-oriented or methods. What is important is how to understand the values and methodologies and construct a maintainable, scalable, stable, and flexible program. No matter whether the white cat or the black cat catches the mouse, it is a good cat.

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.