Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
383 views
in Technique[技术] by (71.8m points)

racket - Using variable-arity function on values-expression

I ran into this toy example recently that has me a bit confused. Suppose I define a simple variable-arity function as below. Then, we are totally within our rights to run this both on one argument and on two.

(define (my-func . a) a)

(my-func 1)  ; evals to '(1)
(my-func 1 2)  ; evals to '(1 2)

The weird bit I've run into is if I try to pass it multiple arguments in one go using values as below:

(my-func (values 1 2))

I'd expect this to evaluate to the same thing as (my-func 1 2), but instead throws an arity-mismatch error, namely that it expected 1 argument but got 2.

Why is it expecting one argument if my-func is variable-arity? Does this have to do with the number of syntactic objects as arguments or is it something else?

question from:https://stackoverflow.com/questions/65873698/using-variable-arity-function-on-values-expression

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In Racket, values construct multiple return values (often abbrev. as multiple values or values). Except the case where it's a single value, values cannot be passed as argument(s). Values can't be kept in a variable. Values are mostly useful when returned from a function, and when used in forms like define-values, etc. See this section of the Racket Reference for more details.

To use the terminology from the above link, (my-func []) is a continuation that only accepts a single value. That's why in your program, it errors with the message "expects one, got two".

What you are trying to do can be accomplished with call-with-values:

(call-with-values (lambda () (values 1 2)) my-func)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...