Home Backend Development Golang Talking about functional programming from Go language closure

Talking about functional programming from Go language closure

Jan 07, 2020 pm 05:44 PM
go

Talking about functional programming from Go language closure

This article learns functional programming from the following aspects:

1. What is the relationship between mathematical formulas and functional programming

Let’s take a simple example. There is a concept in mathematics called mapping (y=f(x)). To put it simply, it is a function. The most familiar one should be the quadratic function (parabola y=a*x*x b*x c)

Now coding implements the value of a certain point on the parabola. We know that a, b, c are parameters, and x is Independent variable, y is the dependent variable. If it were in the past, I might implement it like this (in order to commemorate the c that I haven’t written for a long time, I will write it in c)

double getParabola(double a,double b,double c,double x) {
     return a*x*x+b*x+c;
}
Copy after login

Question 1. Given a parabola, find x =2, x=3, x=4, the value is the following approach

resultA = getParabola(a,b,c,2)
resultB = getParabola(a,b,c,2)
resultC = getParabola(a,b,c,2)
Copy after login

This is a normal approach in the program. However, from a mathematical perspective, is there any way to become consistent with mathematical formula thinking? The following is another implementation of mine (implemented here using go, because I know how to write c),

func getParabola(aa,bb,cc float32){
    var a = aa
    var b = bb
    var c = cc
 
    a := func(x float32) {
           return a*x*x+b*x+c
    }
 
    return a
}
Copy after login

Then, also for question 1, the solution is as follows

parabola := getParabola(a,b,c)
 
resultA := parabola(2)
resultB := parabola(3)
resultC := parabola(4)
Copy after login

is Isn't it the same as finding the value of a function? Therefore, mathematical relationships are well represented in functional programming.

2. What are the characteristics of functional programming and what concepts does go support?

Functional programming has three major characteristics

1. Immutability of variables: Once a variable is assigned a value, it cannot be changed. If changes are needed, they must be copied and then modified. In go, once a string variable is assigned a value, it cannot be modified like c, c[2]='a', but it must be explicitly converted to []byte and then modified. But it is already another piece of memory.

2. Functional first-class citizens: Functions are also variables and can be passed as parameters, return values, etc. in the program. This feature should be supported by both c and go.

3. Tail recursion: The concept of recursion was learned in the Fibonacci sequence. If the recursion is very deep, the stack may explode and cause a significant performance degradation. As for tail recursion optimization technology, if the compiler supports it, the stack can be reused in each recursion (tail recursion means that the recursive call occurs in the last step. At this time, the previous results are passed as parameters to the last step of the call, so the previous The state has no effect anymore, so the stack can be reused).

Commonly used techniques in functional programming

1. map&reduce&filter

map is used to call the same function for each input to produce an output, such as for_each in c, map in hadoop, map in python, etc.

reduce is used to add each input to the previous output to get the next output, such as reduce in python and hadoop,

filter is used for filtering, such as c's count_if, etc. .

2. Recursion

3. Pipeline

Put the function instance into an array or list, and then pass the data to the action list, and the input is sequentially passed to each The function operates (meaning that the output of each function is used as the input of another function, the data is flowing, and the calculation is fixed, similar to the concept of storm), and finally we get the result we want.

4. Others (to be further studied)

3. Functional programming and operating efficiency

The most important concept of functional programming is function Equations are first-class citizens, functions and variables are the same. Can be used as parameters, return values, etc. The use of assignment statements is not favored, so recursion is used more often, so the efficiency of functional programming will definitely be lower.

Recently I use closures more. The concept of closure is an environment (one or more variables) plus a function. Every time the closure expression is evaluated, an isolation is obtained. The result is different from an ordinary function. An ordinary function is a piece of executable code. As long as the entrance is determined, the calling position is also determined. For example, in the parabola example above, calling

a:=getParabola(0.2,0.1,0.3)
b:=getParabola(0.1,0.1,0.4)
Copy after login

will result in two parabolas. The reason why I think the efficiency will be reduced is because the closure itself is a process of evaluation and assignment, involving the creation and destruction of variables. Of course, I didn't actually test the performance. If subsequent release server efficiency decreases, perhaps this is something to consider.

For more go language knowledge, please pay attention to the go language tutorial column on the PHP Chinese website.

The above is the detailed content of Talking about functional programming from Go language closure. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to send Go WebSocket messages? How to send Go WebSocket messages? Jun 03, 2024 pm 04:53 PM

In Go, WebSocket messages can be sent using the gorilla/websocket package. Specific steps: Establish a WebSocket connection. Send a text message: Call WriteMessage(websocket.TextMessage,[]byte("Message")). Send a binary message: call WriteMessage(websocket.BinaryMessage,[]byte{1,2,3}).

In-depth understanding of Golang function life cycle and variable scope In-depth understanding of Golang function life cycle and variable scope Apr 19, 2024 am 11:42 AM

In Go, the function life cycle includes definition, loading, linking, initialization, calling and returning; variable scope is divided into function level and block level. Variables within a function are visible internally, while variables within a block are only visible within the block.

How to match timestamps using regular expressions in Go? How to match timestamps using regular expressions in Go? Jun 02, 2024 am 09:00 AM

In Go, you can use regular expressions to match timestamps: compile a regular expression string, such as the one used to match ISO8601 timestamps: ^\d{4}-\d{2}-\d{2}T \d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-][0-9]{2}:[0-9]{2})$ . Use the regexp.MatchString function to check if a string matches a regular expression.

The difference between Golang and Go language The difference between Golang and Go language May 31, 2024 pm 08:10 PM

Go and the Go language are different entities with different characteristics. Go (also known as Golang) is known for its concurrency, fast compilation speed, memory management, and cross-platform advantages. Disadvantages of the Go language include a less rich ecosystem than other languages, a stricter syntax, and a lack of dynamic typing.

How to avoid memory leaks in Golang technical performance optimization? How to avoid memory leaks in Golang technical performance optimization? Jun 04, 2024 pm 12:27 PM

Memory leaks can cause Go program memory to continuously increase by: closing resources that are no longer in use, such as files, network connections, and database connections. Use weak references to prevent memory leaks and target objects for garbage collection when they are no longer strongly referenced. Using go coroutine, the coroutine stack memory will be automatically released when exiting to avoid memory leaks.

How to view Golang function documentation in the IDE? How to view Golang function documentation in the IDE? Apr 18, 2024 pm 03:06 PM

View Go function documentation using the IDE: Hover the cursor over the function name. Press the hotkey (GoLand: Ctrl+Q; VSCode: After installing GoExtensionPack, F1 and select "Go:ShowDocumentation").

A guide to unit testing Go concurrent functions A guide to unit testing Go concurrent functions May 03, 2024 am 10:54 AM

Unit testing concurrent functions is critical as this helps ensure their correct behavior in a concurrent environment. Fundamental principles such as mutual exclusion, synchronization, and isolation must be considered when testing concurrent functions. Concurrent functions can be unit tested by simulating, testing race conditions, and verifying results.

Things to note when Golang functions receive map parameters Things to note when Golang functions receive map parameters Jun 04, 2024 am 10:31 AM

When passing a map to a function in Go, a copy will be created by default, and modifications to the copy will not affect the original map. If you need to modify the original map, you can pass it through a pointer. Empty maps need to be handled with care, because they are technically nil pointers, and passing an empty map to a function that expects a non-empty map will cause an error.

See all articles