-
-
Save aaronice/870a0993fd4fa2c86b432fed40f1aa4a to your computer and use it in GitHub Desktop.
An answer of the exercise: Fibonacci closure on 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
package main | |
import "fmt" | |
// Very naive answer. | |
// fibonacci is a function that returns | |
// a function that returns an int. | |
func fibonacci() func() int { | |
n := 0 | |
a := 0 | |
b := 1 | |
c := a + b | |
return func() int { | |
var ret int | |
switch { | |
case n == 0: | |
n++ | |
ret = 0 | |
case n == 1: | |
n++ | |
ret = 1 | |
default: | |
ret = c | |
a = b | |
b = c | |
c = a + b | |
} | |
return ret | |
} | |
} | |
func main() { | |
f := fibonacci() | |
for i := 0; i < 10; i++ { | |
fmt.Println(f()) | |
} | |
} |
Author
aaronice
commented
Apr 10, 2019
•
func fibonacci() func() int {
a := 1
b := 0
return func() int {
a, b = b, a+b
return a
}
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment