This is a creation in Article, where the information may have evolved or changed.
Exercise: Fibonacci Closures
Now let's do some interesting things through the function.
Implement a fibonacci
function that returns a function (a closure) that returns a continuous Fibonacci number.
--------------------------------------------------------------------------------------------------------------- -----
The following templates are given:
Package Mainimport the "FMT"//Fibonacci function returns a function that returns INT. Func Fibonacci () func () int {}func main () {f: = Fibonacci () for I: = 0; i <; i++ {FMT. Println (f ())}}
This is the Baidu encyclopedia on the Fibonacci Sequence of interpretation:
Fibonacci number, also known as the Fibonacci sequence (Italian: Successione di Fibonacci), also known as the Golden Section series, Faipot, Faipot, Sinorhizobium fredii series, refers to a series of: 0, 1, 1, 2, 3, 5, 8, 13, 、...... In mathematics, the Fibonacci sequence is defined recursively as follows: F0=0,f1=1,fn=fn-1+fn-2 (n>=2,n∈n*), in words, the Fibonacci sequence starts with 0 and 1, and then the Fibonacci sequence coefficients are added by the previous two numbers.
--------------------------------------------------------------------------------------------------------------- ----------
The program is relatively simple, do not write comments, it is important to note that the first 2 numbers need to be judged by the condition alone
<em>package Mainimport the "FMT"//Fibonacci function returns a function that returns INT. Func Fibonacci () func () int {F0, f1, F2: = 0, 1, 0index: = 0return func () int{if index = = 0 {index + 1return F0} else if index = = 1 {index + = 1return F1} else {F2 = F0 + f1f0 = F1F1 = F2return F2}}}func main () {f: = Fibonacci () for I: = 0; I &l T 10; i++ {fmt. Println (f ())}}</em>