Skip to content

Instantly share code, notes, and snippets.

@royling
Last active December 16, 2015 03:29
Show Gist options
  • Save royling/0e5ddc646e57e5d8ba09 to your computer and use it in GitHub Desktop.
Save royling/0e5ddc646e57e5d8ba09 to your computer and use it in GitHub Desktop.
Implement a fibonacci function that returns a function (a closure) that returns successive fibonacci numbers.
package main
import "fmt"
// fibonacci is a function that returns
// a function that returns an int.
func fibonacci() func() int {
f1, f2 := 0, 1
return func() int {
f1, f2 = f2, f1 + f2
return f1
}
}
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