Go language Development (vi), go language closures

Source: Internet
Author: User
Tags closure

Go language Development (vi), go language closure One, functional programming 1, functional programming Introduction

Functional programming is a programming model that considers computer operations to be calculations of functions in mathematics and avoids the concept of state and variable.
Functional programming has been around for decades before object-oriented thinking is produced. With the increase in hardware performance and improvements in compiler technology and virtual machine technology, some of the dynamic languages that were once constrained by performance issues are beginning to be noticed, and languages such as Python, Ruby, and Lua are beginning to emerge in the application. Dynamic language has become a popular programming language for many people because of its convenient and quick development, and functional programming has been in vogue with the popularity of dynamic language.

2. Features of functional programming

The main features of functional programming are as follows:
A, the variable is immutable: The variable is not changed once the value is assigned. If you need to change it, you must copy it and then modify it.
B, the function is a class citizen: The function is also a variable, can be passed as parameter, return value and so on in the program.
C, tail recursion: If the recursion is very deep, the stack may explode and cause a significant decrease in performance. The tail recursive optimization technique (which requires compiler support) can reuse the stack at each recursive time.

3. High-order function

In functional programming, a function needs to be passed as a parameter, that is, a higher order function. In mathematics and computer science, higher-order functions are functions that meet at least one of the following conditions:
A, the function can be passed as a parameter
B, function can be output as return value

Second, anonymous function 1, anonymous function introduction

An anonymous function is a function implementation that does not need to define a function name, and an anonymous function consists of a function declaration and a function body without a function name. Anonymous functions are not supported in C and C + +.

func(x,y int) int {    return x + y}
2. Value types for anonymous functions

In the go language, all functions are value types, that is, they can be passed as arguments, and can be passed as return values.
An anonymous function can assign a value to a variable:

f := func() int {    ...}

Define a function type:
type CalcFunc func(x, y int) int
Functions can be passed as values:

func AddFunc(x, y int) int {return x + y}func SubFunc(x, y int) int {   return x - y}...func OperationFunc(x, y int, calcFunc CalcFunc) int {   return calcFunc(x, y)}func main() {   sum := OperationFunc(1, 2, AddFunc)   difference := OperationFunc(1, 2, SubFunc)   ...}

The function can be returned as a value:

// 第一种写法func add(x, y int) func() int {   f := func() int {      return x + y   }   return f}// 第二种写法func add(x, y int) func() int {   return func() int {      return x + y   }}

When a function returns multiple anonymous functions, it is recommended to use the first notation:

func calc(x, y int) (func(int), func()) {   f1 := func(z int) int {      return (x + y) * z / 2   }   f2 := func() int {      return 2 * (x + y)   }   return f1, f2}

There are two ways to call anonymous functions:

// 通过返回值调用func main() {   f1, f2 := calc(2, 3)   n1 := f1(10)   n2 := f1(20)   n3 := f2()   fmt.Println("n1, n2, n3:", n1, n2, n3)}// 在匿名函数定义的同时进行调用:花括号后跟参数列表表示函数调用func safeHandler() {   defer func() {      err := recover()      if err != nil {         fmt.Println("some exception has happend:", err)      }   }()   ...}
Three, closure 1, closure of the definition

Functions can be nested definitions (nested functions are typically anonymous functions), meaning that another function can be defined inside a function. The go language supports closures through anonymous functions, and C + + does not support anonymous functions, and in c++11 supports closures through lambda expressions.
Closures are entities that are composed of functions and their associated reference environments (that is, closures = functions + reference environments).
Closures are just like functions in form and expression, but are not actually functions. Functions are executable code, and function code is determined after the function is defined and does not change at execution time, so a function has only one instance. Closures can have multiple instances at run time, and different reference environments and the same combination of functions can produce different instances.
The so-called reference environment is a collection of all active constraints at a point in the execution of a program. A constraint is a relationship between the name of a variable and the object it represents. Because in languages that support nested scopes, it is sometimes not easy to directly determine the reference environment for a function, so you need to combine the reference environment with the function.

2, the nature of closures

Closures are blocks of code that contain free variables that are not defined within the code block or in any global context, but are defined in the context in which the code block is defined. Since the free variable is contained in the code block, the free variable and the referenced object are not freed as long as the closure is used, and the code to be executed provides a binding computing environment for the free variable.
Closures can be used as function objects or as anonymous functions. Most languages that support closures use functions as first-level objects, where functions can be stored in variables as arguments to other functions, and can be dynamically created and returned by functions.

func add(n int) func(int) int {   sum := n   f := func(x int) int {      var i int = 2      sum += i * x      return sum   }   return f}

The function variable in the Add function is F, the free variable is sum, and F provides a binding computing environment for sum, and the code block consisting of sum and F is the closure. The return value of the Add function is a closure, not just the address of the F function. In the Add closure function, only the internal anonymous function f can access the local variable I and cannot be accessed through other means, so the closure guarantees the security of I.
When different closure function variables are obtained by injecting the Add function with different parameters (10, 20), the result is isolated, that is, each time the Add function is called, a new local variable sum is generated and saved.
In a functional language, when an inline function body references a variable outside the body, it will package the reference environment and function body that are involved in the definition as a whole (closure) return.
Each time the Add function is called, a new closure instance is returned, and the different instances are isolated, each containing a different reference environment site at the time of invocation. Unlike functions, closures can have multiple instances at run time, and different reference environments and the same combination of functions can produce different instances.
Formally, the anonymous function is a closed packet.
function is just a piece of executable code, fixed after compiling, each function in memory only one instance, get the function entry point can execute function.
Objects are data that is attached to the behavior, and closures are data-attached behaviors.

3, the use of closed packets

Closures are often used for callback functions, and when IO operations (such as fetching data from the network, file read and write) are completed, some manipulation of the obtained data is performed, and the operation can be given to the function object for processing.
In addition, in some common operations, there are often different special operations, while the differential operation can be encapsulated with a function.

package mainimport "fmt"func adder() func(int) int {   sum := 0   f := func(x int) int {      sum += x      return sum   }   return f}func main() {   sum := adder()   for i := 0; i < 10; i++ {      fmt.Println(sum(i))   }}
Four, closure of the application
package mainimport "fmt"//普通闭包func adder() func(int) int {   sum := 0   return func(v int) int {      sum += v      return sum   }}//无状态、无变量的闭包type iAdder func(int) (int, iAdder)func adder2(base int) iAdder {   return func(v int) (int, iAdder) {      return base + v, adder2(base + v)   }}//使用闭包实现斐波那契数列func Fibonacci() func() int {   a, b := 0, 1   return func() int {      a, b = b, a+b      return a   }}func main() {   //普通闭包调用   a := adder()   for i := 0; i < 10; i++ {      var s int =a(i)      fmt.Printf("0 +...+ %d = %d\n",i, s)   }   //状态 无变量的闭包 调用   b := adder2(0)   for i := 0; i < 10; i++ {      var s int      s, b = b(i)      fmt.Printf("0 +...+ %d = %d\n",i, s)   }   //调用斐波那契数列生成   fib:=Fibonacci()   fmt.Println(fib(),fib(),fib(),fib(),fib(),fib(),fib(),fib())}

Go language Development (vi), go language closures

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.