Skip to content

Instantly share code, notes, and snippets.

@mjg123
Created September 11, 2011 21:27
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mjg123/1210153 to your computer and use it in GitHub Desktop.
Save mjg123/1210153 to your computer and use it in GitHub Desktop.
Truth-table macro in clojure
(defn bool-combinations [vs]
(loop [vs vs
a '({})]
(if (empty? vs)
a
(recur
(rest vs)
(flatten
(map
#(list
(assoc % (first vs) true)
(assoc % (first vs) false))
a))))))
;; problem 46
(defmacro pr-truth-table [vs pred]
`(let [vs2# (filter #(= (name %) (.toUpperCase (name %))) (flatten '~pred))]
(println (apply str (interpose "\t" vs2#)) "\t" '~pred)
(for [{:syms ~vs} (bool-combinations vs2#)]
(println (apply str (interpose "\t" ~vs)) "\t" ~pred))))
(pr-truth-table [A B] (and A (not B)))
;A B (and A (not B))
;true true false
;true false true
;false true false
;false false false
@mjg123
Copy link
Author

mjg123 commented Sep 11, 2011

so, the result of line #22 is as expected, but the first argument to pr-truth-table is redundant. I can infer [A B], as is done on #17. So, now how to change lines #19 and #20 to refer to vs2# not ~vs?

@thaiviet1994
Copy link

Creating a “truth table” is not hard, you can use an useful tool (CKod, at http://ckod.sourceforge.net/_/) to make a “truth table”.

  1. CKod homepage: http://ckod.sourceforge.net/
  2. CKod online: http://ckod.sourceforge.net/_/
  3. CKod forum: http://ckod.sourceforge.net/~/

Good luck to you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment