Created
July 5, 2012 05:44
-
-
Save blakesmith/3051584 to your computer and use it in GitHub Desktop.
Go Tour: Exercise: Exercise: Fibonacci closure - My solution
This file contains 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" | |
// fibonacci is a function that returns | |
// a function that returns an int. | |
func fibonacci() func() int { | |
a := 0 | |
b := 1 | |
f := func() int { | |
s := a | |
a = b | |
b = s + b | |
return s | |
} | |
return f | |
} | |
func main() { | |
f := fibonacci() | |
for i := 0; i < 10; i++ { | |
fmt.Println(f()) | |
} | |
} |
var s
is necessary, the first element of the Fibonacci sequence is 0
so you need to stash a
somewhere before you modify it.
var s is unneccessary,but a, b have to initialize as -1, 1
func fibonoacci() func() int {
a, b := -1, 1
return func() int {
a, b = b, a+b
return b
}
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
var s is unneccessary
a, b := 0, 1
return func() int {
a = a + b
a, b = b, a
return a
}