你能在“if”语句中执行多个语句吗?

时间:2010-05-17 19:49:34

标签: lisp

这是我的功能:

(defun MyFunction(input)
  (let ((NEWNUM (find input num)))
    (if (find input num)              //if this 
      (setq num NEWNUM) (FUNCT2)      //then execute both of these
    (list 'not found))))              //else output this

因此,在if语句后,我希望能够执行(setq num NEWNUM)后跟(FUNCT2)以设置新变量,然后调用函数。关于如何做到这一点的任何想法?

4 个答案:

答案 0 :(得分:41)

要按顺序执行多项操作,您需要progn

(defun MyFunction(input)
  (let ((NEWNUM (find input num)))
    (if (find input num)              //if this 
      (progn 
        (setq num NEWNUM)
        (FUNCT2))      //then execute both of these
    (list 'not found))))              //else output this

答案 1 :(得分:12)

当你的if是'单臂'时,就像他们所说的那样(也就是说,它不包含else分支),使用whenunless通常更容易,更惯用(when pred x y ... z)http://www.cs.cmu.edu/Groups/AI/html/hyperspec/HyperSpec/Body/mac_whencm_unless.html

当您致电x y z时,如果pred为真,它将仅按顺序评估unless。当pred为NIL时,x y z的行为相似。 (when pred (thunk)) 可以表示来自一个向上的任意数量的语句。因此:

(if pred (thunk))

相同
when

有些人说unless(defmacro if/seq (cond then else) `(if ,cond (progn ,@then) (progn ,@else))) 因为清晰而应该始终用于'单臂ifs'。

编辑:你的主题给了我一个想法。这个宏:

(if/seq (find input num)              //if this 
      ((setq num NEWNUM) (FUNCT2))      //then execute both of these
    ((list 'not found))))) 

应启用此功能:

(if/seq *condition* (x y ... z) (a b ... c))

所以一般格式是:

{{1}}

根据条件,它会评估第一个或第二个中的所有子表单,但只返回最后一个。

答案 2 :(得分:6)

您不能对if使用多个语句,除了上面发布的progn。但是有cond形式,

(cond
 ((find input num)     // if this 
  (setq num NEWNUM)    // then execute both of these
  (FUNCT2))

 (t
  (list 'not found)))  // else output this

答案 3 :(得分:1)

只需添加,您还可以使用(begin exp1 exp2 ...)语法依次评估Lisp中的多个表达式。在if的分支上使用它将与使用多个语句具有相同的效果。

相关问题