Are Lisp forms and Lisp expressions same thing?

后端 未结 3 820
别跟我提以往
别跟我提以往 2021-02-07 04:19

Some literature say \"the first subform of the following form...\" or \"to evaluate a form...\" while some other literature say \"To evaluate an expression...\", and most litera

3条回答
  •  鱼传尺愫
    2021-02-07 05:01

    Summary

    A form is Lisp code as data. An expression is data as text.

    See the Glossary entries in the Common Lisp standard:

    • form
    • expression

    Explanation

    In Common Lisp form and expression have two different meanings and it is useful to understand the difference.

    A form is an actual data object inside a running Lisp system. The form is valid input for the Lisp evaluator.

    EVAL takes a form as an argument.

    The syntax is:

    eval form => result*
    

    EVAL does not get textual input in the form of Lisp expressions. It gets forms. Which is Lisp data: numbers, strings, symbols, programs as lists, ...

    CL-USER 103 > (list '+ 1 2)
    (+ 1 2)
    

    Above constructs a Lisp form: here a list with the symbol + as the first element and the numbers 1 and 2 as the next elements. + names a function and the two numbers are the arguments. So it is a valid function call.

    CL-USER 104 > (eval (list '+ 1 2))
    3
    

    Above gives the form (+ 1 2) as data objects to EVAL and computes a result. We can not see forms directly - we can let the Lisp system create printed representations for us.

    The form is really a Lisp expression as a data object.

    This is slightly unusual, since most programming languages are defined by describing textual input. Common Lisp describes data input to EVAL. Forms as data structures.

    The following creates a Lisp form when evaluated:

    "foo"         ; strings evaluate to themselves
    
    'foo          ; that evaluates to a symbol, which then denotes a variable
    
    123
    
    (list '+ 1 2) ; evaluates to a list, which describes a function call
    
    '(+ 1 2)      ; evaluates to a list, which describes a function call
    

    Example use:

    CL-USER 105 > (defparameter foo 42)
    FOO
    
    CL-USER 106 > (eval 'foo)
    42
    

    The following are not creating valid forms:

    '(1 + 2)            ; Lisp expects prefix form
    
    (list 1 '+ 2)       ; Lisp expects prefix form
    
    '(defun foo 1 2)'   ; Lisp expects a parameter list as third element
    

    Example:

    CL-USER 107 > (eval '(1 + 2))
    
    Error: Illegal argument in functor position: 1 in (1 + 2).
    

    The expression is then usually used for a textual version of Lisp data object - which is not necessarily code. Expressions are read by the Lisp reader and created by the Lisp printer.

    If you see Lisp data on your screen or a piece of paper, then it is an expression.

    (1 + 2)             ; is a valid expression in a text, `READ` can read it.
    

提交回复
热议问题