Created
November 18, 2012 19:45
-
-
Save pstoll/4107103 to your computer and use it in GitHub Desktop.
Golang tour 48 fibanacci using a closure
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
| // http://tour.golang.org/#48 | |
| // | |
| package main | |
| import "fmt" | |
| // fibonacci is a function that returns | |
| // a function that returns an int. | |
| func fibonacci() func() int { | |
| prev := 0; | |
| cur := 1 | |
| f := func () int { | |
| s := prev + cur | |
| // nice - swapping via ordered tuple assignment/unpacking | |
| prev, cur= cur, s | |
| return s | |
| } | |
| return f | |
| } | |
| 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