Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Common Lisp: Why progn is a special form?

Tags:

common-lisp

Since Common Lisp's function arguments evaluate in left-to-right order, why wouldn't use an ordinary function:

(defun progn2 (&rest body)
  (first (last body)))

instead of special form?

like image 525
Victor Fedotov Avatar asked Jun 16 '13 20:06

Victor Fedotov


People also ask

What does progn mean in Lisp?

progn is a special form that causes each of its arguments to be evaluated in sequence and then returns the value of the last one. The preceding expressions are evaluated only for the side effects they perform. The values produced by them are discarded.

What are special forms?

A special form is a primitive function specially marked so that its arguments are not all evaluated. Most special forms define control structures or perform variable bindings—things which functions cannot do. Each special form has its own rules for which arguments are evaluated and which are used without evaluation.

What is Progn AutoLISP?

AutoLISP Functions > P Functions > progn. Evaluates each expression sequentially and returns the value of the last expression. (progn [expr]...) You can use progn to evaluate several expressions where only one expression is expected.

What is prog1?

Description: prog1 evaluates first-form and then forms, yielding as its only value the primary value yielded by first-form. prog2 evaluates first-form, then second-form, and then forms, yielding as its only value the primary value yielded by first-form.


2 Answers

There is also another feature of PROGN which you can't get with a function:

Imagine this code in a file of Common Lisp code:

(progn
  (defmacro foo () ))

vs.

(my-progn
  (defmacro foo () ))

With using PROGN the compiler will treat the DEFMACRO form as a top-level form. That means for example that the compiler notes that there is a macro definition and makes it available in the compile-time environment.

Using a function MY-PROGN, the compiler won't recognize the DEFMACRO form, because it is not at top-level.

like image 71
Rainer Joswig Avatar answered Oct 22 '22 09:10

Rainer Joswig


progn returns all the values of the last form it evaluates, your function returns just the first one:

(progn (values 1 2 3)) 
=>  1, 2, 3
(progn2 (values 1 2 3)) 
=>  1

Another critical feature of progn (mentioned by Rainer first) is that it keeps all its forms top-level, which makes it possible for macros to expand to multiple forms (see, e.g., my answer to "“value returned is unused” warning when byte-compiling a macro").

like image 26
sds Avatar answered Oct 22 '22 08:10

sds