~%" "hello" "how ar...">

Justification in a format with a variable number of items in a list

So I can do this:

CL-USER> (format t "~80<~a~;~a~;~a~;~a~>~%" "hello" "how are you" "i'm fine" "no you're not") hello how are you i'm fine no you're not 

It runs 4 rows evenly over a range of 80, as indicated.

However, I want to pass a list of strings and ask them to justify them, based on the fact that many of them are in the list.

None of them do this:

 CL-USER> (format t "~{~80<~a~;~>~}~%" '(1 2 3 4 5 6)) 1 2 3 4 5 6 CL-USER> (format t "~80<~{~a~;~}~>~%" '(1 2 3 4 5 6)) ; Evaluation aborted on #<SB-FORMAT:FORMAT-ERROR {126651E1}>. ; ~; not contained within either ~[...~] or ~<...~> 

Is there any way to do this?

+7
lisp common-lisp
source share
1 answer

You can do this using (format stream (format nil ...)) , where you create a format control to justify using format :

 CL-USER> (format nil (format nil "|~~40<~{~a~^~~;~}~~>|" '(1 2 3 4 5))) "|1 2 3 4 5|" CL-USER> (format nil (format nil "|~~40<~{~a~^~~;~}~~>|" '(1 2 3 4 5 6 7 8 9 10))) "|1 2 3 4 5 6 7 8 9 10|" CL-USER> (format nil (format nil "|~~40<~{~a~^~~;~}~~>|" '(1 2 3 4 5 6 7 8 9 10 11 12 13 14 15))) "|1 2 3 4 5 6 7 8 9 10 11 12 13 14 15|" 

If you do not want to generate the entire size control for an external format , you can use some option ~? to handle a string and some arguments recursively:

 CL-USER> (format nil "| ~@ ?|" (format nil "~~40<~{~a~^~~;~}~~>" '(1 2 3 4 5))) "|1 2 3 4 5|" CL-USER> (format nil "| ~@ ?|" (format nil "~~40<~{~a~^~~;~}~~>" '(1 2 3 4 5 6 7 8 9 10))) "|1 2 3 4 5 6 7 8 9 10|" CL-USER> (format nil "| ~@ ?|" (format nil "~~40<~{~a~^~~;~}~~>" '(1 2 3 4 5 6 7 8 9 10 11 12 13 14 15))) "|1 2 3 4 5 6 7 8 9 10 11 12 13 14 15|" 

Recursive processing with ~? allows you to handle a different control format with a list of arguments; it does not give you the option of splicing in a new line format. It seems like the text that is justified should be present in the control line, so you really need a way to splic in the control line, which already contains the text you want.

Although the first one seems simpler, there is a danger in it because you put the printed text in a different format line, and you do not do this in the second case. In the first case, if any of these numbers has been replaced by format directives, the external format will try to process them. In the second case this does not happen. As such, I think I am proposing a second.

+7
source share

All Articles