Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scheme full padding example using format

Tags:

scheme

racket

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.

like image 927
Lu Ma Avatar asked Aug 22 '14 14:08

Lu Ma


2 Answers

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.

like image 74
Óscar López Avatar answered Oct 14 '22 02:10

Óscar López


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.

like image 3
uselpa Avatar answered Oct 14 '22 03:10

uselpa