schemeguile

"Splicing" `values` in to a function call


Can Scheme "splice" the result of values or a list as the arguments for a function call? For example (imagined syntax): (list 0 (values 1 2) (values 3 4) 5) would return (0 1 2 3 4 5). The apply function isn't very convenient, since it only "splices" its last argument.


Solution

  • apply is the tool for this. Indeed it only splices its last argument, but if you supply it only one argument then you can effectively splice at any position by building the argument list using whatever tool you like. The tool often used for this is "quasiquote" (`), combined with unquote (,) and unquote-splicing (,@).

    For example, to construct your desired list, supposing that (1 2) and (3 4) were variables instead of constants that you could just inline:

    (define xs '(1 2))
    (define ys '(3 4))
    (define args `(0 ,@xs ,@ys 5))
    

    Then you could write (apply f args), with the same effect as (f 0 1 2 3 4 5). And of course you don't need the args variable - this is the same as writing

    (apply f `(0 ,@xs ,@ys 5))