Can you execute multiple statements in an “if” statement?

这一生的挚爱 提交于 2019-11-30 03:27:52

To do several things in sequence, you want 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
Zorf

When your if is 'one-armed', as they call it (that is, it contains no else branch), it's typically easier and more idiomatic to use when and unless: http://www.cs.cmu.edu/Groups/AI/html/hyperspec/HyperSpec/Body/mac_whencm_unless.html

When you call (when pred x y ... z), it will just evaluate x y z sequentially if pred is true. unless behaves similarly when pred is NIL. x y z can represent any number of statements from one upwards. Thus:

(when pred (thunk))

is just the same as

(if pred (thunk))

Some people say when and unless should always be used for 'one-armed-ifs' because of clarity.

Edit: Your thread gave me an idea. This macro:

(defmacro if/seq (cond then else)
  `(if ,cond (progn ,@then) (progn ,@else)))

should enable this:

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

So the general format is:

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

Depending on the condition, it evaluates all of the subforms in the first or second, but only returns the last.

You can't use multiple statements with if, except with progn as posted above. But there is the cond form,

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

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

Just to add, you could also use the (begin exp1 exp2...) syntax to evaluate more than one expression in Lisp sequentially. Using this on an if's branch will have the same effect as using multiple statements.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!