Exercise: Fibonacci closure

Exercise: Fibonacci closure

題目:golang

Let's 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, ...).

代碼:spa

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

運行結果:code

0
1
1
2
3
5
8
13
21
34
相關文章
相關標籤/搜索