问题描述
为什么是:
(apply (car (list 'xor)) '(#t #t))
应用程序:不是程序;期望一个可以应用于参数的过程给定:'异或
application: not a procedure; expected a procedure that can be applied to arguments given: 'xor
(apply (car (list (list 'xor))) '(#t #t))
应用程序:不是程序;期望一个可以应用于参数的过程给定:'(异或)
application: not a procedure; expected a procedure that can be applied to arguments given: '(xor)
(apply (car '(xor #t #t)) (cdr '(xor #t #t)))
应用程序:不是程序;期望一个可以应用于参数的过程给定:'异或
application: not a procedure; expected a procedure that can be applied to arguments given: 'xor
如何将列表的第一个元素应用到列表的其余部分?
How to apply first element of list to rest of list?
推荐答案
在你的程序中,'xor
是一个符号,而不是一个过程.下面的程序中,xor
是指实际的程序,不是符号-
In your program, 'xor
is a symbol, not a procedure. In the program below, xor
refers to the actual procedure, and is not a symbol -
(apply (car (list xor)) (list #t #t))
; #f
(apply (car (list xor)) (list #t #f))
; #t
或者干脆 -
(apply xor (list #t #f))
; #t
当你写'(xor #t #t)
时,xor
被引用并变成符号-
When you write '(xor #t #t)
, xor
is quoted and turned into symbol -
(car '(xor #t #t))
; 'xor
你可以使用准引用 `(...)
但你最不希望引用 ,...
任何你不想转换为符号的东西 - >
You can use quasi-quoting `(...)
but you most unquote ,...
anything you don't want converted to a symbol -
(apply (car `(,xor #t #t)) (cdr `(,xor #t #t)))
; #f
(apply (car `(,xor #t #f)) (cdr `(,xor #t #f)))
; #t
推测 s 表达式将在别处构造 -
Presumably the s-expressions will be constructed elsewhere -
(define sexpr1 (list xor #t #t))
(define sexpr2 (list xor #t #f))
(apply (car sexpr1) (cdr sexpr1)) ;#f
(apply (car sexpr2) (cdr sexpr2)) ;#t
如果 s 表达式包含纯引用数据,您可以eval使用命名空间的表达式.
我们添加了 racket/base
以允许程序应用.程序中的过程 xor
包含在 racket/bool
-
We add racket/base
to allow for procedure application. The procedure in your program, xor
, is included with racket/bool
-
(define (run-sexpr sexpr)
(parameterize ((current-namespace (make-base-empty-namespace)))
(namespace-require 'racket/base)
(namespace-require 'racket/bool)
(eval sexpr)))
(run-sexpr '(xor #t #t)) ;#f
(run-sexpr '(xor #t #f)) ;#t
在我们上面eval
整个 s 表达式,但这可能不是我们想要的.为了使程序工作,我们只需要eval
将'xor
符号变成一个有意义的过程,xor
.这可能最接近您最初的目标 -
Above we eval
the entire s-expression, but this may not be desired. To make the program work, we only need eval
to turn the 'xor
symbol into a meaningful procedure, xor
. This is maybe closest to your original goal -
(define (run-sexpr sexpr)
(parameterize (...)
(...)
(apply (eval (car sexpr)) ;only eval car
(cdr sexpr)))) ;apply cdr verbatim
(run-sexpr '(xor #t #t)) ;#f
(run-sexpr '(xor #t #f)) ;#t
这篇关于如何将列表的第一个元素应用于列表的其余部分?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!