Created
July 14, 2013 05:32
-
-
Save MattSurabian/5993310 to your computer and use it in GitHub Desktop.
Implementation of a Fibonacci Closure in Go. Part of the Go tour: http://tour.golang.org/#43
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 { | |
var m1, m2 int | |
return func() int { | |
res := m1 + m2 | |
m2 = m1 | |
m1 = res | |
if res == 0 { | |
m2 = 1 // Because printing the full sequence is hot | |
} | |
return res | |
} | |
} | |
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