Skip to content

Instantly share code, notes, and snippets.

@blakesmith
Created July 5, 2012 05:44
Show Gist options
  • Save blakesmith/3051584 to your computer and use it in GitHub Desktop.
Save blakesmith/3051584 to your computer and use it in GitHub Desktop.
Go Tour: Exercise: Exercise: Fibonacci closure - My solution
package main
import "fmt"
// fibonacci is a function that returns
// a function that returns an int.
func fibonacci() func() int {
a := 0
b := 1
f := func() int {
s := a
a = b
b = s + b
return s
}
return f
}
func main() {
f := fibonacci()
for i := 0; i < 10; i++ {
fmt.Println(f())
}
}
@ravinwind
Copy link

var s is unneccessary
a, b := 0, 1
return func() int {
a = a + b
a, b = b, a
return a
}

@mu-is-too-short
Copy link

var s is necessary, the first element of the Fibonacci sequence is 0 so you need to stash a somewhere before you modify it.

@crushglass
Copy link

var s is unneccessary,but a, b have to initialize as -1, 1

func fibonoacci() func() int {
a, b := -1, 1
return func() int {
a, b = b, a+b
return b
}
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment