Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
/*
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