开发者

Can you execute multiple statements in an "if" statement?

开发者 https://www.devze.com 2022-12-31 14:44 出处:网络
This is my function: (defun MyFunction开发者_开发知识库(input) (let ((NEWNUM (find input num)))

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?


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消