Skip to content

Instantly share code, notes, and snippets.

@joshuakfarrar
Last active December 15, 2015 05:40
Show Gist options
  • Save joshuakfarrar/b98eb2559f1846c1e197 to your computer and use it in GitHub Desktop.
Save joshuakfarrar/b98eb2559f1846c1e197 to your computer and use it in GitHub Desktop.
;; currying! returns a partially evaluated function
(defn dice [size] (fn [] (+ 1 (rand-int size)))) ;; idiomatic vs using a rand formula
(def d20 (dice 20))
(defn roll-die-until-twenty
([die] (roll-die-until-twenty die 1)) ;; multiple arity
([die attempt]
(let [roll (die)] ;; scoped binding, available only in this lexical scope
(cond ;; https://clojuredocs.org/clojure.core/cond
(= roll 20) attempt
:else (roll-die-until-twenty die (inc attempt))))))
(defn experiment
[]
(roll-die-until-twenty d20))
(defn average-of-results
[results]
(/ (reduce + results) (count results)))
(defn print-report
[average]
(println (format "Average: %f", (float average)))) ;; string interpolation!
(let [results (repeatedly 120000 #(experiment))] ;; no longer crashes at 7500 ~> n <~ 8000 ! :)
(print-report (average-of-results results)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment