Created
September 11, 2011 21:27
-
-
Save mjg123/1210153 to your computer and use it in GitHub Desktop.
Truth-table macro in clojure
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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 | |
Creating a “truth table” is not hard, you can use an useful tool (CKod, at http://ckod.sourceforge.net/_/) to make a “truth table”.
- CKod homepage: http://ckod.sourceforge.net/
- CKod online: http://ckod.sourceforge.net/_/
- 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
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?