I came across the following code to generate permutations of a given string.
package main
import (
"fmt"
)
func main() {
Perm([]rune("abc"), func(a []rune) {
fmt.Println(string(a))
})
}
func Perm(a []rune, f func([]rune)) {
perm(a, f, 0)
}
func perm(a []rune, f func([]rune), i int) {
if i > len(a) {
f(a)
return
}
perm(a, f, i+1)
for j := i + 1; j < len(a); j++ {
a[i], a[j] = a[j], a[i]
perm(a, f, i+1)
a[i], a[j] = a[j], a[i]
}
}
I am having a hard time understanding how this program works. Especially the exit condition where a call is made to f(a)
in func perm. Can someone explain what f(a) implies?
I tried printing fmt.Println(f(a))
but got an error.
Go Playground: https://play.golang.org/p/FNijVw32iAy
You have discovered a Closure!
Also known as an anonymous function.
It is basically a one off function that stays within its scope.
As for the printing not working, that's partly because of the anonymous nature, and partly because it has no return value to print. If you really wanted to get into it, you could try printing &f to generate a pointer so you have a value to print out.