【问题标题】:Can AND/OR use a recursive function to get the value and use it in Common Lisp?AND/OR 可以使用递归函数来获取值并在 Common Lisp 中使用它吗?
【发布时间】:2012-03-15 20:50:24
【问题描述】:

我已经坚持了一段时间。我试过了,但我没有得到它。我以为我明白了,但这不起作用的事实令人困惑。我应该得到 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 规则:

(and x nil) => nil; 
(and nil x) => nil;
(and x 1) => x; 
(and 1 x) => x;

我已经测试过了

(simplify (car(cdr(cdr x))))

我添加了计数以查看它是否均匀循环,但事实并非如此。所以我猜它与第一个代码块中 if 语句中的递归函数调用有关。任何关于为什么的解释将不胜感激。

【问题讨论】:

  • 你能把代码格式化成 Lisp 标准吗?
  • 我试过了,但老实说,重点不是在实际语言之前先学习缩进......这听起来像是你的意思。
  • 如果没有适当的缩进,您的代码将无法阅读。
  • 缩进是普通lisp代码的一部分,就像它们在python代码IMO中一样。有了一个好的编辑器,缩进取代了考虑所有这些括号的需要。我认为代码不可读。
  • setq 不引入局部变量。让。 (eq t (atom foo)) 就是 (atom foo)。 (eq nil (atom foo)) 只是 (not (atom foo))。 EQ 不适用于数字。使用 EQL 或 =。使用 FIRST、SECOND、THIRD 等函数代替重复的 CAR CDR CDR CDR CDR...

标签: function recursion common-lisp


【解决方案1】:
(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))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-08-22
    • 1970-01-01
    • 2018-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多