3

I'm trying to automate some output using printf but I'm struggling to find a way to pass to it the list of arguments expr_1, ..., expr_n in

printf (dest, string, expr_1, ..., expr_n)

I thought of using something like Javascript's spread operator but I'm not even sure I should need it.

For instace, say I have a list of strings to be output

a:["foo","bar","foobar"];

a string of appropriate format descriptors, say

s: "~a ~a ~a ~%";

and an output stream, say os. How can I invoke printf using these things in such a way that the result will be the same as writing

printf(os,s,a[1],a[2],a[3]);

Then I could generalize it to output lists of variable size.

Any suggestions?

Thanks.

EDIT:

I just learned about apply and, using the conditions I posed in my OP, the following seems to work wonderfully:

apply(printf,append([os,s],a));
booNlatoT
  • 571
  • 3
  • 14

1 Answers1

6

Maxima printf implements most or maybe all of the formatting operators from Common Lisp FORMAT, which are quite extensive; see: http://www.lispworks.com/documentation/HyperSpec/Body/22_c.htm See also ? printf in Maxima to get an abbreviated list of formatting operators.

In particular for a list you can do something like:

printf (os, "my list: ~{~a~^, ~}~%", a);

to get the elements of a separated by ,. Here "~{...~}" tells printf to expect a list, and ~a is how to format each element, ~^ means omit the inter-element stuff after the last element, and , means put that between elements. Of course , could be anything.

There are many variations on that; if that's not what you're looking for, maybe I can help you find it.

Robert Dodier
  • 16,905
  • 2
  • 31
  • 48