4 ms·
Works intuitively in golang: https://play.golang.org/p/pn2jBTaTNS8 https://play.golang.org/p/pn2jBTaTNS8 package main import ( "fmt" ) // ret
by loopz 7y ago
Works intuitively in golang:
https://play.golang.org/p/pn2jBTaTNS8 https://play.golang.org/p/pn2jBTaTNS8
package main
import (
"fmt"
)
// return a^n
func Power(a, n int) int {
var i, result int
result = 1
for i = 0; i < n; i++ {
result *= a
}
return result
}
func main() {
fmt.Println("Hello, playground")
x := 2
var powers_of_x []int
for i := 0; i < 10; i++ {
powers_of_x = append(powers_of_x, func(x int) int { return Power(x, i) }(x))
}
fmt.Println(powers_of_x)
}
//Output:
//Hello, playground
//[1 2 4 8 16 32 64 128 256 512]
- gpderetta 7y agoI know nothing about go, but it seems to me in your example powers_of_x is a list of n integers, while in the example being discussed is an list of n functions (which can be used to compute the n'th power).
- masklinn 7y agoI provided a Go example demonstrating that it does not. Your version 1. uses a slice of integers which completely misses the point 2. uses an IIFE which completely misses the point The point is to look at what happens when you close over the iteration variable.