What is the difference between quote and list?

前端 未结 2 1533
孤城傲影
孤城傲影 2020-11-22 15:37

I know that you can use \' (aka quote) to create a list, and I use this all the time, like this:

> (car \'(1 2 3))
1
         


        
2条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-22 15:48

    The behavior you are seeing is a consequence of Scheme not treating symbols as functions.

    The expression '(+ - * /) produces a value which is a list of symbols. That's simply because (+ - * /) is a list of symbols, and we are just quoting it to suppress evaluation in order to get that object literally as a value.

    The expression (list + - * /) produces a list of functions. This is because it is a function call. The symbolic expressions list, +, -, * and / are evaluated. They are all variables which denote functions, and so are reduced to those functions. The list function is then called, and returns a list of those remaining four functions.

    In ANSI Common Lisp, calling symbols as functions works:

    [1]> (mapcar (lambda (f) (funcall f 1)) '(+ - * /))
    (1 -1 1 1)
    

    When a symbol is used where a function is expected, the top-level function binding of the symbols is substituted, if it has one, and everything is cool.

    If you want to use list to produce a list of symbols, just like '(+ - * /), you have to quote them individually to suppress their evaluation:

    (list '+ '- '* '/)
    

    you will see that if you map over this, it will fail in the same way.

    The error message you are being shown is misleading:

    expected a procedure that can be applied to arguments
    given: '+
    

    The applicator was not given (quote +) at all, but +. What's going on here is that the symbol + is being printed in "print as expression" mode, which is a feature of Racket, which is what I guess you're using.

    In "print as expression" mode, objects are printed using a syntax which must be read and evaluated to produce a similar object. See the StackOverflow question "Why does the Racket interpreter write lists with an apostroph before?"

提交回复
热议问题