Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- (declare fibo-m)
- (defn fibo [n]
- (if (<= n 2)
- 1
- (+ (fibo-m (- n 1)) (fibo-m (- n 2)))))
- (def fibo-m (memoize fibo))
- ;; ---------------------------------------------------------
- ;; the (fibo-m 35) should NOT be slow, it has alreay been
- ;; calculated by the previous call to (fibo-m 36)
- ;; what would be the idiomatic clojure way to apply memoize
- ;; to fibo such as the recursives call inside fibo body get
- ;; memoized as-well ?
- ;; ---------------------------------------------------------
- ;; for comparaison i put the working equivalent in python:
- def memo(f, cache={}):
- def caching_func(n):
- if n not in cache:
- cache[n] = f(n)
- return cache[n]
- return caching_func
- @memo
- def fibo(n):
- """
- i know it's not an efficient way to do fibo
- it's just made for example purpose
- """
- if n <= 2:
- return 1
- return fibo(n - 1) + fibo(n - 2)
- ######################
- import time
- def time_it(f, *args):
- start = time.clock()
- print f(*args)
- return (time.clock() - start)
- print time_it(fibo, 500)
- # Elapsed time: 0.004
- #= 139423224561697880139724382870407283950070256587697307264108962948325571622863290691557658876222521294125
- print time_it(fibo, 499)
- # Elapsed time: 0.0
- #= 86168291600238450732788312165664788095941068326060883324529903470149056115823592713458328176574447204501
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement