[racket] Filling number

From: Laurent (laurent.orseau at gmail.com)
Date: Fri Sep 28 09:45:29 EDT 2012

On Fri, Sep 28, 2012 at 3:13 PM, <heraklea at gmx.de> wrote:

> Thank you,
>
> I write my first lambda ;o). What about this:
> (define string->mformat
>   (lambda (str)
>     (lambda (n)
>         (lambda (filler)   (if (equal? (string-length str) n)
>                           str
>                           (((string->mformat (string-append  filler str))
> n) filler))))))
>
> It only prepends, but is this style ok??
>

It depends if you are required to have a particular style (for class, for
example), but your code can be rewritten more conveniently (with some
subtle differences though) to:
(define (string->mformat str n filler)
  (if (equal? (string-length str) n)
      str
      (string->mformat (string-append filler str) n filler)))

Equivalently:
(define string->mformat
  (lamda (str n filler) ....
  ))

Some would prefer to use cond instead of if, but in this particular case
that's mainly a matter of taste I believe.

It is also possible to use build-string, without using explicit recursion:
(define (string->mformat str n filler)
  (string-append
   (build-string (max 0 (- n (string-length str)))
                 (lambda (x) filler))
   str))

Laurent


>
> Yours,
>
> -------- Original-Nachricht --------
> > Datum: Thu, 27 Sep 2012 16:26:00 +0200
> > Von: Laurent <laurent.orseau at gmail.com>
> > An: heraklea at gmx.de
> > CC: racket <users at racket-lang.org>
> > Betreff: Re: [racket] Filling number
>
> > Hi,
> >
> > Looking for a friend of real->decimal-string (which does only partly what
> > you want), I see that the nightly builds include a family of value
> > formatters like ~a, ~v, etc.
> > You probably want ~r, for example:
> > > (~r 42 #:min-width 5 #:pad-string "0")
> > "00042"
> >
> > They have many options that should fit your needs.
> >
> > Cheers,
> > Laurent
> >
> > On Thu, Sep 27, 2012 at 4:11 PM, <heraklea at gmx.de> wrote:
> >
> > > Hello friends,
> > >
> > > I search the docu, but I cannot find how I can fill a number with
> > leading
> > > zeros or trailing zeros.
> > >
> > > I am using number->string and would like fill the missing zeros.
> > >
> > > Yours,
> > > ____________________
> > >   Racket Users list:
> > >   http://lists.racket-lang.org/users
> > >
> ____________________
>   Racket Users list:
>   http://lists.racket-lang.org/users
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.racket-lang.org/users/archive/attachments/20120928/3c555ad4/attachment.html>

Posted on the users mailing list.