Skip to content

Instantly share code, notes, and snippets.

@twsiyuan
Last active June 13, 2017 08:39
Show Gist options
  • Save twsiyuan/8af390ea9752e863d07cefe71f1b0f27 to your computer and use it in GitHub Desktop.
Save twsiyuan/8af390ea9752e863d07cefe71f1b0f27 to your computer and use it in GitHub Desktop.
exercise-fibonacci-closure.go
package main
import "fmt"
// fibonacci is a function that returns
// a function that returns an int.
func fibonacci() func() int {
n := 0
fn2 := 1
fn1 := 1
return func() int{
switch n {
case 0:
n += 1
return 0
case 1, 2:
n += 1
return 1
}
fn := fn2 + fn1
fn2 = fn1
fn1 = fn
return fn
}
}
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