Reputation: 147
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.
Upvotes: 6
Views: 1472
Reputation: 48765
Scheme doesn't have a format
procedure, but one is available in SRFI-48. It is not compatible with either MIT Scheme nor #!racket (the language).
#!r6rs
(import (rnrs base)
(srfi :48))
(format "~4F " "x") ; ==> " x"
You can use SRFI-48 with #!racket in similar manner:
#!racket
(require srfi/48)
(format "~4F " "x") ; ==> " x"
F
works only for numbers and strings according to the documentation:
~[w[,d]]F Fixed ~w,dF outputs a number with width w and d digits after the decimal; ~wF outputs a string or number with width w.
Also by evaluating (format "~h")
you get instructions for use so for the basic reminder on syntax you don't need to visit the SRFI page.
Upvotes: 1
Reputation: 236112
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.
Upvotes: 5
Reputation: 18927
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.
Upvotes: 3