all
I want to change a element to formatted string, then I use format function. (the language I use is scheme )
As the document in http://www.gnu.org/software/mit-scheme/documentation/mit-scheme-ref/Format.html said, I can use ~mincolA if I want inserts spaces on the right.
So I use
(format "~4A " x)
but I get an error like that:
format: ill-formed pattern string
explanation: tag `~4' not allowed
pattern string: "~4A "
I want to get the result like below:
if x is 0, then the result is space space space 0;
if x is 12, then the result is space space 12.
I know I can use
(string-append (make-string (- 4 (string-length x)) #\ ) x)
to get the result I want, but I really want use "format" function.
Thanks.
Notice that the referenced documentation is for MIT/GNU Scheme, the format
function works different in Racket. Out-of-the-box, you can use the ~a
function for the same effect:
(~a x #:min-width 4 #:align 'right #:left-pad-string " ") ; x can be a number or a string
For example:
(~a 0 #:min-width 4 #:align 'right #:left-pad-string " ")
=> " 0"
(~a "12" #:min-width 4 #:align 'right #:left-pad-string " ")
=> " 12"
If you don't mind importing an additional external library, @uselpa's answer is spot-on.
You can use the format
procedure from SRFI 48:
> (require srfi/48)
> (format "~4F" 0)
" 0"
> (format "~4F" 12)
" 12"
If you want to keep the original format
procedure along with this one, you can give the one from SRFI 48 a prefix:
> (require (prefix-in srfi48: srfi/48))
> (srfi48:format "~4F" 0)
so the original format
is still available.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With