Skip to content

Instantly share code, notes, and snippets.

@tetsuok
Created April 2, 2012 08:48
Show Gist options
  • Save tetsuok/2281812 to your computer and use it in GitHub Desktop.
Save tetsuok/2281812 to your computer and use it in GitHub Desktop.
An answer of the exercise: Fibonacci closure on a tour of Go
package main
import "fmt"
// Very naive answer.
// fibonacci is a function that returns
// a function that returns an int.
func fibonacci() func() int {
n := 0
a := 0
b := 1
c := a + b
return func() int {
var ret int
switch {
case n == 0:
n++
ret = 0
case n == 1:
n++
ret = 1
default:
ret = c
a = b
b = c
c = a + b
}
return ret
}
}
func main() {
f := fibonacci()
for i := 0; i < 10; i++ {
fmt.Println(f())
}
}
@vallekaz
Copy link

package main

import "fmt"


// fibonacci is a function that returns
// a function that returns an int.
func fibonacci() func(int) int {
	return func(x int) int {
		 
		switch x {
		case 0:
			return 0
		case 1:
			return 1
		default:
			return fibonacci()(x-1) + fibonacci()(x-2)
		}
	}

}


func main() {

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

DAP server listening at: 127.0.0.1:65035
0
1
1
2
3
5
8
13
21
34
Process 36798 has exited with status 0

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