August 19, 2024

P48 - Truth tables for logical expressions (3)

Generalize problem P47 in such a way that the logical expression may contain any number of logical variables. Define table in a way that (table List Expr) prints the truth table for the expression Expr, which contains the logical variables enumerated in List.

Example:* (table '(A B C) '((A and (B or C)) equ ((A and B) or (A and C)))).true true true truetrue true nil truetrue nil true truetrue nil nil truenil true true truenil true nil truenil nil true truenil nil nil true

lisp

(defun table (vars expr)
(print (table0 () vars expr))
(print-table (table0 () vars expr))
)

(defun print-table (l)
(dolist (line l)
(dolist (v (car line))
(format t "~S " v)
)
(format t "~S~%" (cadr line))
)
)

(defun table0 (prefix vars expr)
"Print table with every line preceeded with prefix"
(if (null vars)
(list (list (reverse prefix) (bool-infix-eval expr)))
(append (table0 (cons t   prefix) (cdr vars) (subst t   (car vars) expr))
(table0 (cons nil prefix) (cdr vars) (subst nil (car vars) expr))
)
)
)

;;; Esta funcao avalia uma expressao infixa E
;;; com conectivos not, and or, xor, impl, equ e
;;; constantes t e nil

(defun bool-infix-eval (e)
(cond
((eql e nil) nil)
((eql e t) t)
((not (consp e)) 'invalida)
((eql (first e) 'not) (not (bool-infix-eval (second e))))
((eql (second e) 'and) (and (bool-infix-eval (first e))
(bool-infix-eval (third e))
))
((eql (second e) 'or) (or (bool-infix-eval (first e))
(bool-infix-eval (third e))
))
((eql (second e) 'xor) (xor (bool-infix-eval (first e))
(bool-infix-eval (third e))
))
((eql (second e) 'impl) (impl (bool-infix-eval (first e))
(bool-infix-eval (third e))
))
((eql (second e) 'equ) (equ (bool-infix-eval (first e))
(bool-infix-eval (third e))
))
(t 'invalida)
)
)
Be first to comment
Leave a reply