common-lisp Prog1 and Prog2


Example

Often times, it is helpful to evaluate multiple expressions and to return the result from the first or second form rather than the last. This is easy to accomplish using let and, for instance:

(let ((form1-result form1))
  form2
  form3
  ;; ...
  form-n-1
  form-n
  form1-result)

Because this form is common in some applications, Common Lisp includes prog1 and prog2 that are like progn, but return the result of the first and second forms, respectively. For instance:

(prog1
  42
  (print 'hello)
  (print 'goodbye))
;; => 42
(prog2
  (print 'hello)
  42
  (print 'goodbye))
;; => 42

An important distinction between prog1/prog2 and progn, however, is that progn returns all the values of the last form, whereas prog1 and prog2 only return the primary value of the first and second form. For instance:

(progn
  (print 'hello)
  (values 1 2 3))
;;=> 1, 2, 3

(prog1
  (values 1 2 3)
  (print 'hello))
;;=> 1              ; not 1, 2, 3

For multiple values with prog1 style evaluation, use multiple-value-prog1 instead. There is no similar multiple-value-prog2, but it is not difficult to implement if you need it.