Skip to content

Instantly share code, notes, and snippets.

@zerogvt
Created February 6, 2019 10:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zerogvt/e590409692bb65acee845aafa480d155 to your computer and use it in GitHub Desktop.
Save zerogvt/e590409692bb65acee845aafa480d155 to your computer and use it in GitHub Desktop.
/*
Exercise: Fibonacci closure
Let's have some fun with functions.
Implement a fibonacci function that returns a function (a closure) that returns successive fibonacci numbers (0, 1, 1, 2, 3, 5, ...).
https://tour.golang.org/moretypes/26
*/
package main
import "fmt"
// fibonacci is a function that returns
// a function that returns an int.
func fibonacci() func() int {
m := make(map[int]int)
m[0] = 0
m[1] = 0
return func() int {
res := m[0] + m[1]
m[0] = m[1]
if res != 0 {
m[1] = res
} else {
m[1] = 1
}
return res
}
}
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