99 Clojure Problems (48)
Yesterday I was moping that I wasn’t able to do problem 48. Luckily for me, commenter Mark was able to show me that apply can be used to take each item of a list as separate parameters to that function. (Instead of taking the whole list.)
This gives me the following:
; P48 (**) Truth tables for logical expressions (3). (comment "Generalize problem P47 in such a way that the logical expression may contain any number of logical variables. Define table/2 in a way that table(List,Expr) prints the truth table for the expression Expr, which contains the logical variables enumerated in List.") (defn truth-table [n] (loop [nleft n combos (list (list ))] (if (zero? nleft) combos (recur (dec nleft) (concat (map #(conj % true) combos) (map #(conj % false) combos)))))) (defn table2 [nparams func] (let [tfls (truth-table nparams)] (doseq [ls tfls] (do (doseq [t ls] (print t "\t")) (println (apply func ls))))))
So, while it still doesn’t use the operator syntax, it does take any number of arguments as long as you tell it how many arguments there are. I’m happy with this solution, because I learned something doing it.