A Tour of Go Exercise: Fibonacci closure

时间:2014-10-28 00:37:06   收藏:0   阅读:129

Let‘s have some fun with functions.

Implement a fibonacci function that returns a function (a closure) that returns successive fibonacci numbers.

package main

import "fmt"

// fibonacci is a function that returns
// a function that returns an int.
func fibonacci() func() int {
    before := 0
    now := 0
    return func() int {
        if before == 0 {
            before++
            return before
        }
        if now == 0 {
            now++
            return now
        }
        temp := now
        now = before + now
        before = temp
        return now 
    }
}

func main() {
    f := fibonacci()
    for i := 0; i < 10; i++ {
        fmt.Println(f())
    }
}

 

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!