Doing the fibonacci closure example
but I'm too sleepy to figure out the right way to make the first two yielded values 1's.
This commit is contained in:
parent
d23bfcc869
commit
b53879a0fb
23
gotime/src/exercise-fibonacci-closure.go
Normal file
23
gotime/src/exercise-fibonacci-closure.go
Normal file
@ -0,0 +1,23 @@
|
||||
package main
|
||||
|
||||
import "fmt"
|
||||
|
||||
// fibonacci is a function that returns
|
||||
// a function that returns an int.
|
||||
func fibonacci() func() int {
|
||||
prev := 0
|
||||
cur := 1
|
||||
return func() int {
|
||||
old_cur := cur
|
||||
cur = prev + cur
|
||||
prev = old_cur
|
||||
return cur
|
||||
}
|
||||
}
|
||||
|
||||
func main() {
|
||||
f := fibonacci()
|
||||
for i := 0; i < 10; i++ {
|
||||
fmt.Println(f())
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user