Created
November 15, 2012 09:44
-
-
Save parasyte/4077694 to your computer and use it in GitHub Desktop.
Fibonacci closure: http://tour.golang.org/#48
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 { | |
x, y := 0, 1 | |
return func() int { | |
x, y = y, x + y | |
return x | |
} | |
} | |
func main() { | |
f := fibonacci() | |
for i := 0; i < 10; i++ { | |
fmt.Println(f()) | |
} | |
} |
package main
import "fmt"
// fibonacci is a function that returns
// a function that returns an int.
func fibonacci() func() int {
i := 0
iOne := int(1)
ret := 0
return func() int {
if i == 0{
i = 1
}
iOne = ret
ret = i + iOne
i = iOne
return ret
}
}
func main() {
f := fibonacci()
for i := 0; true; i++ {
fmt.Println(f())
}
}
func fibonacci() func() int {
x, y := -1, 0
return func() int {
x, y = y, x + y
return (-1) * x
}
}
package main
import "fmt"
func main() {
a := 0
for i:=1; i<=1000; {
fmt.Println(i)
a, i = i, i+a
}
}
func fibonacci() func() int {
a := 0
b := 1
return func() int {
defer func() {
fib := a+b
a = b
b = fib
}()
return a
}
}
func main() {
f := fibonacci()
for i := 0; i < 10; i++ {
fmt.Println(f())
}
}
func Fibonacci() func() uint {
var a, b uint = 1, 0
return func() uint {
a, b = b, a+b
return a
}
}
thanks for the gist,it is very much useful
I make Benchmarking for deferent Fibonacci functions and algorithms with running unit test
https://github.com/msh2050/GoFibonacciBench
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
package main