Created
October 26, 2020 22:08
-
-
Save gerrywastaken/d662b512a84770b085baee73a542701a to your computer and use it in GitHub Desktop.
Answer to Exercise: Fibonacci closure in A Tour of Go
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
# An answer to https://tour.golang.org/moretypes/26 | |
# This is a bit more readable than other examples that I found online | |
# Implement a fibonacci function that returns a function (a closure) that returns successive fibonacci numbers (0, 1, 1, 2, 3, 5, ...). | |
package main | |
import "fmt" | |
// fibonacci is a function that returns | |
// a function that returns an int. | |
func fibonacci() func() int { | |
prev, current := -1, 1 | |
return func() int { | |
prev, current = current, prev+current | |
return current | |
} | |
} | |
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