From 9ce988f0e6e15ca97f5b5fb1def317ec8fb8eba2 Mon Sep 17 00:00:00 2001 From: Jian Han Date: Thu, 19 Apr 2018 21:50:54 +1000 Subject: [PATCH] cache added --- functional_programming/ch01/fibonacci.go | 28 ++++++++++++++++++++---- functional_programming/ch01/memoized.go | 1 + 2 files changed, 25 insertions(+), 4 deletions(-) create mode 100644 functional_programming/ch01/memoized.go diff --git a/functional_programming/ch01/fibonacci.go b/functional_programming/ch01/fibonacci.go index fa08d94..f87d6a0 100644 --- a/functional_programming/ch01/fibonacci.go +++ b/functional_programming/ch01/fibonacci.go @@ -2,17 +2,37 @@ package main import "fmt" -func Fibonacci(x int) int { +type Memoized func(int) int + +var fibMem = Memoize(fib) + +func Memoize(mf Memoized) Memoized { + cache := make(map[int]int) + return func(key int) int { + if val, found := cache[key]; found { + return val + } + temp := mf(key) + cache[key] = temp + return temp + } +} + +func FibMemoized(n int) int { + return fibMem(n) +} + +func fib(x int) int { if x == 0 { return 0 } else if x <= 2 { return 1 } else { - return Fibonacci(x-2) + Fibonacci(x-1) + return fib(x-2) + fib(x-1) } } func main() { - fib := Fibonacci - fmt.Printf("%vn", fib(50)) + fmt.Println(fib(30)) + fmt.Println(FibMemoized(30)) } diff --git a/functional_programming/ch01/memoized.go b/functional_programming/ch01/memoized.go new file mode 100644 index 0000000..06ab7d0 --- /dev/null +++ b/functional_programming/ch01/memoized.go @@ -0,0 +1 @@ +package main