Skip to content

Instantly share code, notes, and snippets.

@viebel
Last active August 8, 2016 18:45
Show Gist options
  • Save viebel/b431422131fa042e1d05fee1ec268151 to your computer and use it in GitHub Desktop.
Save viebel/b431422131fa042e1d05fee1ec268151 to your computer and use it in GitHub Desktop.
Y combinator applications in clojure: memo and printer
(def Y (fn [f]
((fn [x]
(x x))
(fn [x]
(f (fn [y]
((x x) y)))))))
(defn memo []
(let [hist (atom {})]
(fn [f]
(fn [y]
(if (find @hist y)
(@hist y)
(let [res (f y)]
(swap! hist assoc y res)
res))))))
(defn printer [f]
(fn [y]
(println "printer: " y)
(f y)))
(def Ywrap
(fn [wrapper-func f]
((fn [x]
(x x))
(fn [x]
(f (wrapper-func (fn [y]
((x x) y))))))))
(def Ymemo
(fn [f]
(Ywrap (memo) f)))
(def factorial-gen (fn [func]
(fn [n]
(println n)
(if (zero? n)
1
(* n (func (dec n)))))))
(def fact-memo (Ymemo factorial-gen))
(fact-memo 4)
(fact-memo 4)
(def Yprinter (partial Ywrap printer))
(def fact-printer (Yprinter factorial-gen))
(fact-printer 7)
(defn fib-nr [f]
(fn [n]
(if (< n 2) 1
(+ (f (- n 1))
(f (- n 2))))))
(defn fib [n]
(if (< n 2) 1
(+ (fib (- n 1))
(fib (- n 2)))))
(def n 30)
(time (fib n))
(time ((Y fib-nr) n))
(time ((Ymemo fib-nr) n))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment