From 1bade734cf63dba9eee9569ca84c7b077480e758 Mon Sep 17 00:00:00 2001 From: "Stephen M. McQuay" Date: Thu, 2 Aug 2012 16:06:12 -0600 Subject: [PATCH] added fibonacci closure exercise solution --- exercises/03-fibonacci/fibonacci.go | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 exercises/03-fibonacci/fibonacci.go diff --git a/exercises/03-fibonacci/fibonacci.go b/exercises/03-fibonacci/fibonacci.go new file mode 100644 index 0000000..2544afb --- /dev/null +++ b/exercises/03-fibonacci/fibonacci.go @@ -0,0 +1,29 @@ +package main + +import "fmt" + +// fibonacci is a function that returns +// a function that returns an int. +// from cpython/Doc/build/html/library/functools.html +// [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610] +func fibonacci() func() int { + cur_fib := 0 + nxt_fib := 0 + return func() int { + if nxt_fib == 0 { + nxt_fib = 1 + return 0 + } + tmp := cur_fib + cur_fib = nxt_fib + nxt_fib += tmp + return cur_fib + } +} + +func main() { + f := fibonacci() + for i := 0; i < 20; i++ { + fmt.Println(f()) + } +}