码迷,mamicode.com
首页 > 其他好文 > 详细

Exercise: Fibonacci closure

时间:2016-05-24 13:37:49      阅读:463      评论:0      收藏:0      [点我收藏+]

标签:

Exercise: Fibonacci closure

题目:

Lets have some fun with functions.

Implement a fibonacci function that returns a function (a closure) that returns successive fibonacci numbers (0, 1, 1, 2, 3, 5, ...).

代码:

package main

import "fmt"

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

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

运行结果:

0
1
1
2
3
5
8
13
21
34

  

  

Exercise: Fibonacci closure

标签:

原文地址:http://www.cnblogs.com/chpx/p/5523010.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!