Created
February 6, 2019 10:03
-
-
Save zerogvt/e590409692bb65acee845aafa480d155 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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