Skip to content

Instantly share code, notes, and snippets.

@joshgo
Created March 28, 2014 14:20
Show Gist options
  • Save joshgo/9833985 to your computer and use it in GitHub Desktop.
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
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