The first version of this blog entry incorrectly stated that the idiomatic Go code was recursive. Thanks to Andrew Gerrand, of the Go team at Google, for pointing out my error.
I've become a big fan of Go. If you don't know about it, check it out at Go Language.
Test Results
Here is the code:
//memo.py
//From Python Algorithms by Magnus Lie Heitland
from functools import wraps
def memo(func):
cache = {}
@wraps(func)
def wrap(*args):
if args not in cache:
cache[args] = func(*args)
return cache[args]
return wrap
//fibonacci.py
from memo import memo
import sys
@memo # Comment this out for the first set of tests.
def fib(i):
if i < 1:
return 1
return fib(i - 1) + fib(i - 2)
def main():
n = int(sys.argv[1])
print fib(n)
if __name__ == "__main__":
main()
//fibonacci_recr.go
package main
import (
"fmt"
"os"
"strconv"
)
func fib(n int64) int64 {
if n <= 1 {
return n
}
return fib(n-1) + fib(n-2)
}
func main() {
n, _ := strconv.Atoi64(os.Args[1])
for i := int64(1); i <= n; i++ {
fmt.Println(fib(i))
}
}
//Fibonacci.java
public class Fibonacci {
public static long fib(int n) {
if (n <= 1) return n;
else return fib(n-1) + fib(n-2);
}
public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
for (int i = 1; i <= N; i )
System.out.println(i + ": " + fib(i));
}
}
//fibonacci.go
package main
import (
"os"
"strconv"
)
func fib() func() int64 {
var a,b int64
a, b = 0,1
return func() int64 {
a, b = b, a+b
return a
}
}
func main() {
a := os.Args[1]
N, err := strconv.Atoi(a)
if err != nil {
println(err)
return
}
f := fib()
for i := 0; i <= N; i {
println(f())
}
}