From 3c04bc59d7b766f818ed5050c3ab5e2509bc56a4 Mon Sep 17 00:00:00 2001 From: AJ ONeal Date: Mon, 6 Aug 2012 18:37:28 -0600 Subject: [PATCH] added golang --- fibonacci.go | 76 +++++++++++++++++++++++++++++++++++++++++++++++ fibonacci.tour.go | 21 +++++++++++++ 2 files changed, 97 insertions(+) create mode 100644 fibonacci.go create mode 100644 fibonacci.tour.go diff --git a/fibonacci.go b/fibonacci.go new file mode 100644 index 0000000..e3574ec --- /dev/null +++ b/fibonacci.go @@ -0,0 +1,76 @@ +package main + +import ( + "flag" + "fmt" + "strconv" +) + +var max int +var ch chan int + +func fib(a, b int) { +//func fib(a, b int, bag []int) { + //append(bag, a) + ch <- a + //fmt.Println(a) + + if b > max { + ch <- b + //append(bag, b) + //fmt.Println(b) + } else { + fib(b, a + b) + } +} + +func fibloop() { + a, b := 1, 1 + + ch <- a + ch <- b + //fmt.Println(a) + //fmt.Println(b) + + for b < max { + a, b = b, a + b + ch <- b + //fmt.Println(b) + } +} + +func printStuff() { + for { + i := <-ch + fmt.Println(i) + } +} + +func main() { + flag.Parse() + + var e error + ch = make(chan int) + + go printStuff() + + // stop counting once we get over 100 (or a user-set max) + if 0 == flag.NArg() { + max = 100 + } else { + max, e = strconv.Atoi(flag.Args()[0]) + } + + if nil != e { + fmt.Println("argument must be an integer") + return + } + + fmt.Println("recursively...") + fib(1, 1) + + fmt.Println("") + + fmt.Println("iteratively...") + fibloop() +} diff --git a/fibonacci.tour.go b/fibonacci.tour.go new file mode 100644 index 0000000..9ba61ec --- /dev/null +++ b/fibonacci.tour.go @@ -0,0 +1,21 @@ +package main + +import "fmt" + +// fibonacci is a function that returns +// a function that returns an int. +func fibonacci() func() int { + a := 0 + b := 1 + return func () int { + a, b = b, a + b; + return a; + } +} + +func main() { + f := fibonacci() + for i := 0; i < 10; i++ { + fmt.Println(f()) + } +}