Skip to content

Instantly share code, notes, and snippets.

@timsgardner
Created November 10, 2016 06:20
Show Gist options
  • Save timsgardner/1db7e671fd542c6c47ec35345934d974 to your computer and use it in GitHub Desktop.
Save timsgardner/1db7e671fd542c6c47ec35345934d974 to your computer and use it in GitHub Desktop.
prob cond
(defmacro prob-cond [& clauses]
(let [valsym (gensym "val_")
test-vals (reductions + (take-nth 2 clauses))]
`(let [~valsym (* ~(last test-vals) (rand))]
(cond
~@(mapcat (fn [tv clause] `[(<= ~valsym ~tv) ~clause])
test-vals
(take-nth 2 (rest clauses)))))))
(prob-cond
2 :hi
2 :there
3 :marty)
;; expands to:
(let* [val_1329 (* 7 (rand))]
(cond
(<= val_1329 2) :hi
(<= val_1329 4) :there
(<= val_1329 7) :marty))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment