Created
October 8, 2014 12:11
-
-
Save arialdomartini/f1ec3b10dcc95e2d3195 to your computer and use it in GitHub Desktop.
Tail recursive Fibonacci
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 { | |
a1 := 0 | |
a2 := 1 | |
return func() int { | |
a1, a2 = fib(a1, a2) | |
return a2 | |
} | |
} | |
func fib(a1 int, a2 int) (int, int) { | |
return a2, a1 + a2 | |
} | |
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