Skip to content

Instantly share code, notes, and snippets.

@Liangdi
Created April 16, 2012 17:00
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Liangdi/2399968 to your computer and use it in GitHub Desktop.
Save Liangdi/2399968 to your computer and use it in GitHub Desktop.
Go语言练习:斐波纳契闭包
package main
import "fmt"
// via http://www.talaland.com/go-tour-fibonacci/
// fibonacci 函数会返回一个返回 int 的函数。
func fibonacci() func() int {
//count 用于计数调用次数,只要考虑0和1,不知有没有其他更好的方法
    //sum1 和 sum2 用于储存 fib函数的两次和的值
    var count,sum1,sum2 int= 0,1,1
    return func() int {
        switch count {
            //0 和 1 fib=1
            case 0,1:
                count++
            //其他 fib(n) = fib(n-1) + fib(n-2)
            default:
                sum1,sum2 = sum2,sum1+sum2
        }
        return sum2
    }
}
func main() {
    f := fibonacci()
    for i := 0; i < 10; i++ {
        fmt.Println(f())
    }
}
@mgbaozi
Copy link

mgbaozi commented Aug 28, 2013

func fibonacci() func() int {
var x, y int = -1, 1
return func() int {
x, y = y, x + y
return y
}
}
It isn't necessary to use "switch".

@uinz
Copy link

uinz commented Dec 12, 2016

func fibonacci() func() int {
	a, b := -1, 1
	return func() int {
		a, b = b, a+b
		return b
	}
}

@OneYX
Copy link

OneYX commented Oct 17, 2018

func fibonacci() func() int {
	a, b := 1, 0
	return func() int {
		a, b = b, a+b
		return b
	}
}

@doublnt
Copy link

doublnt commented May 5, 2019

@mgbaozi Good Job

@Belyenochi
Copy link

func fibonacci() func() int {
	prev := 0
	curr := 0
	
	return func(index int) func() int {
		return func() int {
			if index == 1 {
				curr = 1
			} else {
				temp := curr
				curr = temp + prev
				prev = temp
			}

			index ++
			return curr
		}
	}(0)
}

@YUNZHONGTAN
Copy link

@mgbaozi Good Job

@figozhu
Copy link

figozhu commented Jan 9, 2020

func fibonacci() func() int {
var x, y int = -1, 1
return func() int {
x, y = y, x + y
return y
}
}
It isn't necessary to use "switch".

uncorrect

var x, y int = 1, 0

@rainzhao
Copy link

rainzhao commented Sep 8, 2020

func fibonacci() func(int) int {
    return func(i int) int {
        switch i {
        case 0:
            return 0
        case 1, 2:
            return 1
        default:
            return fibonacci()(i-1) + fibonacci()(i-2)
        }
    }
}

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

@TsGanT
Copy link

TsGanT commented Jun 7, 2021

func fibonacci() func(x int) int {
start := make([]int,0,15)
start = append(start, 0)
start = append(start, 1)
res := func(x int) int {
start = append(start, start[x] + start[x+1])
return start[x]
}
return res
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment