Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
480 views
in Technique[技术] by (71.8m points)

lisp - How does `if` not evaluate all its arguments?

I'm trying to learn and understand the Lisp programming language to a deep level. The function + evaluates its arguments in applicative order:

(+ 1 (+ 1 2))

(+ 1 2) will be evaluated and then (+ 1 3) will be evaluated, but the if function works differently:

(if (> 1 2) (not-defined 1 2) 1)

As the form (not-defined 1 2) isn't evaluated, the program doesn't break.

How can the same syntax lead to different argument evaluation? How is the if function defined so that its arguments aren't evaluated?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

if is a special operator, not an ordinary function.

This means that the normal rule that the rest elements in the compound form are evaluated before the function associated with the first element is invoked is not applicable (in that it is similar to macro forms).

The way this is implemented in a compiler and/or an interpreter is that one looks at the compound form and decides what to do with it based on its first element:

  • if it is a special operator, it does its special thing;
  • if it is a macro, its macro-function gets the whole form;
  • otherwise it is treated as a function - even if no function is defined.

Note that some special forms can be defined as macros expanding to other special forms, but some special forms must actually be present.

E.g., one can define if in terms of cond:

(defmacro my-if (condition yes no) 
  `(cond (,condition ,yes)
         (t ,no)))

and vice versa (much more complicated - actually, cond is a macro, usually expanding into a sequence of ifs).

PS. Note that the distinction between system-supplied macros and special operators, while technically crisp and clear (see special-operator-p and macro-function), is ideologically blurred because

An implementation is free to implement a Common Lisp special operator as a macro. An implementation is free to implement any macro operator as a special operator, but only if an equivalent definition of the macro is also provided.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...