Created
March 28, 2014 14:20
-
-
Save joshgo/9833985 to your computer and use it in GitHub Desktop.
Messing around with Go fibonacci example. Making the function successive forwards and backwards. #golang
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
| package main | |
| import "fmt" | |
| // fib returns a function that returns | |
| // successive Fibonacci numbers. | |
| func fib() func(int) int { | |
| a, b := 0, 1 | |
| i := 0 | |
| return func(x int) int { | |
| if x == i { | |
| return a | |
| } else if x < i { | |
| for ; x < i; i-- { | |
| a, b = b-a, a | |
| } | |
| } else { | |
| for ; x > i; i++ { | |
| a, b = b, a+b | |
| } | |
| } | |
| return a | |
| } | |
| } | |
| func main() { | |
| f := fib() | |
| // Function calls are evaluated left-to-right. | |
| fmt.Println(f(1), f(2), f(3), f(4), f(5), f(4), f(3), f(2), f(1), f(6), f(7), f(4)) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment