Skip to content

Instantly share code, notes, and snippets.

@arialdomartini
Created October 8, 2014 12:11
Show Gist options
  • Save arialdomartini/f1ec3b10dcc95e2d3195 to your computer and use it in GitHub Desktop.
Save arialdomartini/f1ec3b10dcc95e2d3195 to your computer and use it in GitHub Desktop.
Tail recursive Fibonacci
package main
import "fmt"
// fibonacci is a function that returns
// a function that returns an int.
func fibonacci() func() int {
a1 := 0
a2 := 1
return func() int {
a1, a2 = fib(a1, a2)
return a2
}
}
func fib(a1 int, a2 int) (int, int) {
return a2, a1 + a2
}
func main() {
f := fibonacci()
for i := 0; i < 10; i++ {
fmt.Println(f())
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment