首页 > 其他 > 详细

A Tour of Go Exercise: Fibonacci closure

时间:2014-10-28 00:35:04      阅读:281      评论:0      收藏:0      [点我收藏+]

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())
    }
}

 

A Tour of Go Exercise: Fibonacci closure

原文:http://www.cnblogs.com/ghgyj/p/4055566.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!