Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
A Tour of Go: Exercise: Fibonacci closure, https://go-tour-jp.appspot.com/moretypes/26
package main
import "fmt"
// fibonacci is a function that returns
// a function that returns an int.
func fibonacci() func() int {
var i int
var n [3]int
return func() int {
defer func() { i++ }()
if i < 2 {
n[i] = i
return i
} else {
n[2] = n[0] + n[1]
n[0], n[1] = n[1], n[2]
return n[2]
}
}
}
func main() {
f := fibonacci()
for i := 0; i < 10; i++ {
fmt.Println(f())
}
}
Owner

takatoshiono commented Aug 31, 2016

きっとこれがベストアンサー http://qiita.com/yanap/items/a20944631e3dc8ebab56
こんなの思いつかないわ。読んでなるほどってなる

Owner

takatoshiono commented Aug 31, 2016

きっとこれがベストアンサー

と思ったけどこれだと最初の0を返せないなあ

Owner

takatoshiono commented Aug 31, 2016

代入部分をdeferすればよいな(defe使いたいマンになってる)

func fibonacci() func() int {
    a := 0
    b := 1
    return func() int {
        defer func() { a, b = b, a+b }()
        return a
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment