Skip to content

Instantly share code, notes, and snippets.

@dhoss
Created November 18, 2013 18:56
Show Gist options
  • Save dhoss/7533287 to your computer and use it in GitHub Desktop.
Save dhoss/7533287 to your computer and use it in GitHub Desktop.
Tour of Go (http://tour.golang.org) fibonacci with closures
package main
import "fmt"
// fibonacci is a function that returns
// a function that returns an int.
func fibonacci() func(int) int {
fib := make([]int, 100)
fib[0] = 0
fib[1] = 1
return func(n int) int {
if n < 2 {
return n
}
fib[n] = fib[n-1]+fib[n-2]
return fib[n]
}
}
func main() {
f := fibonacci()
for i := 0; i < 10; i++ {
fmt.Println(f(i))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment