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

Bra*_*ble 25 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
Run Code Online (Sandbox Code Playgroud)

所以在if声明之后我希望能够执行,(setq num NEWNUM)然后(FUNCT2)设置一个新变量,然后调用一个函数.关于如何做到这一点的任何想法?

Chu*_*uck 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
Run Code Online (Sandbox Code Playgroud)

  • 您也可以使用`prog1`代替`progn`,它将返回第一个表达式的值. (2认同)

Zor*_*orf 12

当你if是"独臂",他们称之为(即,它不包含任何else分支),它通常更容易,更地道使用whenunless:http://www.cs.cmu.edu/Groups/AI/html /hyperspec/HyperSpec/Body/mac_whencm_unless.html

当你打电话时(when pred x y ... z),它只是x y z按顺序评估是否pred为真.unlesspredNIL 时表现相似.x y z可以代表一个向上的任意数量的陈述.从而:

(when pred (thunk))
Run Code Online (Sandbox Code Playgroud)

就像是一样的

(if pred (thunk))
Run Code Online (Sandbox Code Playgroud)

有些人说when并且unless应该总是因为清晰而被用于"单臂ifs".

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

(defmacro if/seq (cond then else)
  `(if ,cond (progn ,@then) (progn ,@else)))
Run Code Online (Sandbox Code Playgroud)

应该启用这个:

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

所以一般格式是:

(if/seq *condition* (x y ... z) (a b ... c))
Run Code Online (Sandbox Code Playgroud)

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


小智 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
Run Code Online (Sandbox Code Playgroud)