Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Sign up for free
Menu
Search
Features
All features
Private URLs
Password Protection
Custom URLS
Scheduled publishing
Remove Branding
Restrict embedding
Deck Collections
Notes
Features
All features
Private URLs
Password Protection
Custom URLS
Scheduled publishing
Remove Branding
Restrict embedding
Deck Collections
Notes
Explore
Featured decks
Featured speakers
Programming
Technology
Storyboards
Explore
Featured decks
Featured speakers
Programming
Technology
Storyboards
Pricing
Search
Sign in
Sign up for free
Exploring Clojure with Factorials
Search
Noah Zucker
September 19, 2012
Programming
150
0
Share
Embed
Copy iframe code
Copy JS code
Copy link
Start on current slide
Exploring Clojure with Factorials
Presentation to Clojure NYC meetup , Sept 2012
Noah Zucker
September 19, 2012
Other Decks in Programming
See All in Programming
全ての永続トークンを、生まれる前に消し去りたい!
sylph01
2
890
IBM Bob でAI駆動開発『QC-Playbook』
ichirokano2
0
110
気持ちぃ〜角丸 Squircle
ryu1013
0
310
【加筆修正版】Laravel のアプリケーションをどこにデプロイするか #phpcon_ehime
akase244
0
150
[Rails World 2026] Durable orchestration on Rails: from continuation to workflow
palkan
1
750
Railsバージョンを4倍にした話
optim
0
360
Railsのためのパスキー実践入門 〜マルチテナントSaaSでの意思決定〜
utakaha
2
560
Vue Fes Japan の “作る側”に関わってみて
naokihaba
0
160
R8 の設定見直しでアプリサイズ削減
andpad
0
220
なぜCTOを降りてFDEを選んだのか?〜なぜプロダクト企業がFDEで顧客の現場に踏み込むのか〜
gonta
1
210
SalesForceを内製化!? ~ HR事業を支える顧客管理基盤のインフラを大公開 ~
oku053
0
180
UnityでSystem.Net.WebSocketsなWebSocketサーバが動かないのでUnity Monoのコードを覗いてみた / about implementing websocket server with unity mono
drumath2237
1
610
Featured
See All Featured
Responsive Adventures: Dirty Tricks From The Dark Corners of Front-End
smashingmag
254
22k
How People are Using Generative and Agentic AI to Supercharge Their Products, Projects, Services and Value Streams Today
helenjbeal
2
360
How to optimise 3,500 product descriptions for ecommerce in one day using ChatGPT
katarinadahlin
PRO
3
3.9k
Rebuilding a faster, lazier Slack
samanthasiow
85
9.7k
The Art of Delivering Value - GDevCon NA Keynote
reverentgeek
16
2.2k
A brief & incomplete history of UX Design for the World Wide Web: 1989–2019
jct
2
530
Building Flexible Design Systems
yeseniaperezcruz
330
41k
Faster Mobile Websites
deanohume
310
32k
Hiding What from Whom? A Critical Review of the History of Programming languages for Music
tomoyanonymous
3
1.3k
What’s in a name? Adding method to the madness
productmarketing
PRO
24
4.2k
Primal Persuasion: How to Engage the Brain for Learning That Lasts
tmiket
0
500
Reality Check: Gamification 10 Years Later
codingconduct
0
2.3k
Transcript
Exploring Clojure with Factorials Noah Zucker @noahlz /
[email protected]
Factorials in Java
public static int calculate(int n) { if(n == 1) return
1; int result = 1; for (int i = n; i > 1; i--) { result *= i; } return result; }
public static int calculateRecursively(int n) { if(n == 0) return
1; return (n * calculateRecursively(n - 1)); }
Clojure: First Steps
(defn factorial-using-recur [n] (loop [current n next (dec current) total
1] (if (> current 1) (recur next (dec next) (* total current)) total)))
user=> (* 1 2 3 4 5) 120
(defn factorial-using-apply-range [n] (apply * (range 1 (inc n))))
(defn factorial-using-apply-iterate [n] (apply * (take n (iterate inc 1))))
(defn factorial-using-reduce [n] (reduce * (range 1 (inc n))))
Higher Order Functions ♦ “Data is Code”
(defn make-fac-function [n] (fn [] (reduce * (range 1 (inc
n)))))
user=> (def fac5 (make-fac-function 5)) #'user/fac5 user=> (fac5) 120
(defn factorial-using-eval-and-cons [n] (eval (cons '* (range 1 (inc n)))))
user=> (def fac-expr (cons '* (range 1 6))) #'user/fac-expr user=>
fac-expr (* 1 2 3 4 5) user=> (eval fac-expr) 120
(defmacro factorial-function-macro [n] `(fn [] (* ~@(range 1 (inc n)))))
user=> (macroexpand '(factorial-function-macro 5)) (fn* ([] (clojure.core/* 1 2 3
4 5))
Effective Java
public interface ValueComputer<T> { T compute(); }
public class Factorial implements ValueComputer<Integer> { private final int; private
Factorial(int n) { this.n = n; } public Integer compute() { return calculate(n); } }
public static class Builder { private int n; public Builder
factorial(int n) { this.n = n; return this; } public Factorial build() { return new Factorial(n); } }
Factorial.Builder builder = new Factorial.Builder(); builder.factorial(5); ValueComputer computer = builder.build();
System.out.println("5! = " + computer.compute());
Java Interop
(defn factorial-using-javainterop [n] (example.Factorial/calculate n))
(import 'example.Factorial$Builder) (defn factorial-using-javainterop-and-pipeline [n] (-> (Factorial$Builder.) (.factorial n) .build
.compute))
user=> (clojure.walk/macroexpand-all '(-> (Factorial$Builder.) (.factorial 5) .build .compute)) (. (.
(. (new Factorial$Builder) factorial 5) build) compute) Equivalent: (.compute (.build (.factorial (new Factorial$Builder) 5))))
(defn newFactorialComputer [n] (reify example.ValueComputer (compute [this] (factorial-using-reduce n))))
(require '[incanter.core :only factorial]) (defn factorial-from-incanter [n] (incanter.core/factorial n)) (http://incanter.org)
Clojure Concurrency in Practice
(defn factorial-using-ref-dosync [n psz] (let [result (ref 1) parts (partition-all
psz (range 1 (inc n))) tasks (for [p parts] (future (Thread/sleep (rand-int 10)) (dosync (alter result #(apply * % p)))))] (dorun (map deref tasks)) @result))
(defn factorial-using-agent [n psz] (let [result (agent 1) parts (partition-all
psz (range 1 (inc n)))] (doseq [p parts] (send result #(apply * % p))) (await result) @result))
(defn factorial-using-pmap-reduce [n psz] (let [parts (partition-all psz (range 1
(inc n))) sub-factorial-fn #(apply * %)] (reduce * (pmap sub-factorial-fn parts))))
Rube-Goldberg Factorials
(declare facseq) (defn factorial-using-lazy-seq [n] (nth (facseq) n)) (defn- facseq
([] (facseq 1 1)) ([n v] (let [next-n (inc n) next-v (* n v)] (cons v (lazy-seq (facseq next-n next-v))))))
(defrecord Factorial [n value]) (defmulti factorial-using-multimethods (fn ([limit] true) ([limit
{:keys [n]}] (< n limit))))
(defmethod factorial-using-multimethods true ([limit] (factorial-using-multimethods limit (new Factorial 1 1)))
([limit fac] (let [next-factorial (-> fac (update-in [:n] inc) (update-in [:value] #(* % (:n fac))))] (factorial-using-multimethods limit next-factorial)))
(defmethod factorial-using-multimethods false ([limit fac] (* limit (:value fac))))
(defn factorial-for-trampoline [n] (letfn [(next-fac-value [limit current-step previous-value] (let [next-value
(* current-step previous-value)] (if (= limit current-step) next-value #(next-fac-n limit current-step next-value)))) (next-fac-n [limit previous-step current-value] #(next-fac-value limit (inc previous-step) current-value))] (next-fac-value n 1 1)))
user=> (trampoline (factorial-for-trampoline 5)) 120
(defn factorial-using-areduce [n] (let [arr (long-array n)] (dotimes [i n]
(aset-long arr i (inc i))) (areduce arr idx ret (long 1) (* ret (aget arr idx)))))
http://github.com/noahlz/factorials
EPILOGUE
Don't Do This! (defn factorial-using-do-while [n] (do (def a 0)
(def res 1) (while (< a n) (def a (inc a)) (def res (* res a))) res))