Skip to content

Instantly share code, notes, and snippets.

@moogzy
Last active November 15, 2016 10:56
Show Gist options
  • Save moogzy/2c3879e477bcf6729033632258703a56 to your computer and use it in GitHub Desktop.
Save moogzy/2c3879e477bcf6729033632258703a56 to your computer and use it in GitHub Desktop.
package main
import "fmt"
// fibonacci is a function that returns
// a function that returns an int.
//
// (aru): I don't believe this is a true closure either?
// or if it is...that it is more complex than it needs to be.
func fibonacci_naive() func(int) int {
// Seed values for current and previous fibonacci numbers.
curr, prev := 0, 1
return func(x int) int {
// O is always the starting number, so if x == 0 just return 0
if x == 0 {
return x
// When x isn't 0 let's perform the Fibonacci sequence magic
} else {
// New value of x becomes sum of curr + prev values
x = curr + prev
// Set prev to current curr for next call of function
prev = curr
// Set curr to x(sum of curr + prev) so we can return it
curr = x
return curr
}
}
}
// This is closing over the curr and next values (keeping state across function calls)
func fibonacci_proper_closure() func() int {
// Seed values
curr, next := 0, 1
return func() int {
// Set fibsum to curr to set return value
fibsum := curr
// Set curr and next values to appropriate/correct fib seq values.
curr, next = next, next + curr
return fibsum
}
}
func main() {
// Call naive closure.
fn := fibonacci_naive()
for i := 0; i < 20; i++ {
fmt.Printf("%d, ", fn(i))
}
// Make the output pretty.
fmt.Println()
// Call decent(proper) closure.
fpc := fibonacci_proper_closure()
for i := 0; i < 20; i++ {
fmt.Printf("%d, ", fpc())
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment