Skip to content

Instantly share code, notes, and snippets.

@fgui
Created November 12, 2015 10:58
Show Gist options
  • Save fgui/dc0f1b1f4c69dceaadcd to your computer and use it in GitHub Desktop.
Save fgui/dc0f1b1f4c69dceaadcd to your computer and use it in GitHub Desktop.
playing with doing iterate without sequence and memoize
(ns recur.ns-hof)
(defn f-nth-iterate
[f init]
(fn fun-nth
([val left]
(if (zero? left) val
(recur (f val) (dec left))
))
([e] (fun-nth init e))))
(defn memoize-fun-nth [f-nth]
(let [mem (atom {})]
(fn [e] (let [nth-value
(if-let [last-know
(first (filter #(<= % e) (sort > (keys @mem))))]
(f-nth (@mem last-know) (- e last-know))
(f-nth e))]
(swap! mem assoc e nth-value)
nth-value))))
(comment
((f-nth-iterate inc 0) 10)
(def inc-nth (memoize-fun-nth (f-nth-iterate inc 0)))
(inc-nth 10)
(defn fib-iter[[n-1 n]] [n (+ n-1 n)])
(def fib-nth (memoize-fun-nth (f-nth-iterate fib-iter [0N 1N])))
(time (first (fib-nth 100000)))
(time (first (fib-nth 100100)))
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment