Closure in Go, C++ and Scheme

In Go, function is a first-class type, so there comes “function literal”, like the constant (or literal) values of types like int, float and string. It is thus possible to assign function literals, and function literals server as exactly “closure” known in some other programming languages like Scheme.

[C++ does not yet support closure, although there is a proposal in C++0x standard. However, people argue that the template meta-programming in C++ is pure functional, and thus can support closure as Scheme and other functional programming languages. You might want to refer to this article about meta-programming and closure.]

Here is an example of closure in Go:

package main

import (
	"fmt"
)

var a func()
var i int = 10
var j int = 20

func main() {
	func() {
		var i int = 100
		a = func() {
			fmt.Printf("Hello World: %d\n", i + j);
		}
	}()
	i *= 2
	j *= 2
	a()
}

The function literal starting in L12 and ending at L17 is invoked by the pair of parenthesis in L17. This invocation leads to an assignment of another function literal, from L14 to L16, to global variable a, which becomes a closure, and is invoked in L20.

If you build and run above program, it would print “Hello World: 140”. Why? Let us look closer. The function literal defined in L14 depends on symbols “fmt.Printf”, “i”, and “j”; “fmt.Printf” is bound to a function defined in package “fmt”, “i” is bound to the integer variable defined in L13, and “j” is bounded to the variable defined in L9. So, when the closure, a, is invoked in L20, it prints the sum of the value bound to “i” (100) and that to “j” (40).

Some more words: we used the word “bound” in above paragraph. In a dynamic scoped language, the opposite to “bound” is “free” — a symbol or a name is either “bound” or “free”. We also talked about “closure”, whose opposite is “open” — if an expression has all its symbols bound, it is closed, otherwise it is open. For more about “bound”, “free”, “close” and “open”, I would suggest this post by Max Hailperin on comp.lang.scheme.