Skip to content

Instantly share code, notes, and snippets.

@uraimo
Created June 2, 2013 09:38
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save uraimo/5693154 to your computer and use it in GitHub Desktop.
Save uraimo/5693154 to your computer and use it in GitHub Desktop.
A Tour of Go: Fibonacci closure solution
package main
import "fmt"
// fibonacci is a function that returns
// a function that returns an int.
func fibonacci() func() int {
a,b := 0,1
return func() int{
res := a
tmp := b+a
a, b = b,tmp
return res
}
}
func main() {
f := fibonacci()
for i := 0; i < 10; i++ {
fmt.Println(f())
}
}
@uraimo
Copy link
Author

uraimo commented Jun 2, 2013

Ok, no need for a temp var and can be further compacted

package main

import "fmt"

// fibonacci is a function that returns
// a function that returns an int.
func fibonacci() func() int {
    a,b,res := 0,1,0
    return func() int{
        res, a, b = a, b, b+a
        return res
    }
}

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