Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Control padding programmatically in Clojure format (java.util.Formatter), cl-format (Common Lisp format)?

Is there a way to use Clojure forrmat (based on java.util.Formatter) or cl-format (based on Common Lisp's format) to set space padding programmatically? If you know the desired width in advance these both return " foo":

(format "%6s" "foo")
(clojure.pprint/cl-format nil "~6d" "foo")

But what if I want the program to decide how wide the returned string should be? Obviously I can construct the format string by hand, e.g.:

(def width 6)
(format (str "%" width "s") "foo")

But I thought I remembered that there was a Common Lisp format directive that could simply insert the value of a format argument into a format directive, and then use the resulting constructed directive to process the next argument. However, I haven't yet found such a directive in the CL Hyperspec or CLTL2 (which doesn't mean that the information is not there). Nor have I discovered such a directive in the java.util.Formatter documentation, so far. Is there a way to control directives with directives in any of these formatting functions/classes?

(I'm not sure whether my cl-format example is supposed to work, since d is a number-formatting directive. It does work in Clojure 1.5.1. The same trick works in CLISP with format, but not in SBCL, ABCL, CCL, or ECL.)

Edit: (I've discovered that the correct way to left-pad a string is by adding @ to the a directive, rather than by using d:

(clojure.pprint/cl-format nil "~6@a" "foo")

This method should always work in Common Lisp, and by using @a rather than d in Clojure, one avoids the risk that a future implementation of cl-format will change the behavior of d with strings, which is an unintended use.)

like image 311
Mars Avatar asked Nov 24 '25 15:11

Mars


1 Answers

In Common Lisp, you can use v as a prefix parameter, e.g.:

(format nil "~vd" 10 42)

It's documented here: http://clhs.lisp.se/Body/22_c.htm

In place of a prefix parameter to a directive, V (or v) can be used. In this case, format takes an argument from args as a parameter to the directive.

like image 51
Lars Brinkhoff Avatar answered Nov 26 '25 03:11

Lars Brinkhoff



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!