Can you execute multiple statements in an “if” sta

2020-02-18 21:30发布

问题:

This is my function:

(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

So after the if statement I want to be able to execute (setq num NEWNUM) followed by (FUNCT2) in order to set a new variable and then call a function. Any ideas on how to do this?

回答1:

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


回答2:

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.



回答3:

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


回答4:

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.



标签: lisp