我被困在这一段时间了。我试过了,我没有得到它。我以为我得到了它,但事实上这不起作用令人困惑。我应该得到1,但一直都是零。目的是使用规则简化表达式(我在下面添加)。我的问题:
(defun simplify (main-list)
(setq count 1)
(if (and (eq t (atom (car (cdr main-list))))
(eq t (atom (car (cdr (cdr main-list))))))
(print "this says that the 2 ands are cons cells"))
(if (and (eq nil (cdr main-list))
(eq t (atom (car main-list))))
(print "reached end of file, going back now"))
(if (eq 'and (car main-list))
(progn
(if (and (eq t (atom (car (cdr main-list))))
(eq nil (atom (car (cdr (cdr main-list))))))
(if (or (eq nil (car (cdr main-list)))
(simplify (car (cdr (cdr main-list)))))
nil
(if (eq 1 (car (cdr main-list)))
(simplify (car (cdr (cdr main-list))))
(if (eq 1 (simplify (car (cdr (cdr main-list)))))))))
(if (and (eq t (atom (car (cdr main-list))))
(eq t (atom (car (cdr (cdr main-list))))))
(if (or (eq nil (car (cdr main-list)))
(eq nil (car (cdr (cdr main-list)))))
nil
(if (eq 1 (car (cdr main-list)))
(car (cdr (cdr main-list)))
(if (eq 1 (car (cdr (cdr main-list))))
(car (cdr main-list)))))))))
我使用的列表是:
(and 1 (and 1 1))
这是我想要完成的一个简单版本,但我正在逐步解决这个问题,因为我完全不熟悉该语言。这些是我想要遵循的家庭作业的规则:
(and x nil) => nil;
(and nil x) => nil;
(and x 1) => x;
(and 1 x) => x;
我已经通过
测试了它(simplify (car(cdr(cdr x))))
我添加了计数以查看它是否均匀循环,但事实并非如此。所以我的猜测它与第一个代码块中if语句中的递归函数调用有关。对于为什么会有任何解释将不胜感激。
答案 0 :(得分:0)
(defun simplify (expression)
(if (consp expression)
(destructuring-bind (op arg1 arg2)
expression
(ecase op
(and (cond ((or (null arg1) (null arg2))
nil)
((eql 1 arg1)
(simplify arg2))
((eql 1 arg2)
(simplify arg1))))))
expression))