Created
February 12, 2015 03:45
-
-
Save waddles/53e06925227a796fa932 to your computer and use it in GitHub Desktop.
Go Tour Exercise on Closures - a Fibonacci sequence generator - http://tour.golang.org/moretypes/22
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 { | |
seq := []int{0,1} | |
i := 0 | |
return func() int { | |
seq = append(seq, seq[i] + seq[i + 1]) | |
i++ | |
return seq[i - 1] | |
} | |
} | |
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