简体   繁体   中英

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:

(define (plus1 . x) (+ x 1))
(define (sum-all . l) (apply + l))

sum-all function can then be used as follows:

(sum-all 1 2 3)     ; => 6
(sum-all . (1 2 3)) ; => 6

However, this does not work for 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. On the other hand, (sum-two 1 2 . ()) is.

In the definition of (plus1 . x) , x is intended to be a list in plus1 's body. Indeed, applying plus1 to any argument will result in a run-time error.

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 .

However, when you're calling that function, calling it as (func . 1) doesn't mean anything at all. That's why it's a syntax error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM