[英]Why applying functions using the pair “dot” notation can be a syntax error in Racket?
In Racket, the following form of defining functions is supported: 在Racket中,支持以下形式的函数定义:
(define (plus1 . x) (+ x 1))
(define (sum-all . l) (apply + l))
sum-all
function can then be used as follows: 然后可以使用sum-all
函数:
(sum-all 1 2 3) ; => 6
(sum-all . (1 2 3)) ; => 6
However, this does not work for plus1
: 但是,这不适用于plus1
:
(plus1 . 0) ; bad syntax error
Similarly, 同样的,
(define (sum-two a . b) (+ a b))
(sum-two 1 . 2) ; bad syntax error
Why is this syntax not allowed? 为什么不允许这种语法?
An application form needs to be of the form of a proper list, which (sum-two 1 . 2)
is not. 申请表必须是正确列表的形式,而不是(sum-two 1 . 2)
。 On the other hand, (sum-two 1 2 . ())
is. 另一方面, (sum-two 1 2 . ())
是。
In the definition of (plus1 . x)
, x
is intended to be a list in plus1
's body. 在(plus1 . x)
的定义中, x
旨在成为plus1
正文中的列表。 Indeed, applying plus1
to any argument will result in a run-time error. 的确,将plus1
应用于任何参数将导致运行时错误。
Within a define
form, (define (func . args) body)
means that whatever arguments you give to func
, they are to be put into a single list, named args
. 在define
形式中, (define (func . args) body)
意味着无论您给func
提供什么参数,它们都将被放入一个名为args
列表中。
However, when you're calling that function, calling it as (func . 1)
doesn't mean anything at all. 但是,当您调用该函数时,将其调用为(func . 1)
根本没有任何意义。 That's why it's a syntax error. 这就是为什么这是语法错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.