I started with Ryan's code from `~r` and tried to emulate some special
cases I see the C code (and didn't worry about negative numbers) and
ended up with something 4-5x slower than the C code version. :( Code
follows.
Robby
#lang racket
(define (number->string* N)
(cond [(zero? N)
(string #\0)]
[else
(let* ([short-size 10]
[str (make-string short-size)])
(let loop ([N N] [digits null] [i short-size])
(cond
[(zero? N)
(if (<= i 0)
(if (null? digits)
str
(string-append (apply string digits) str))
(substring str i short-size))]
[else
(define-values (q r) (quotient/remainder N 10))
(define d (integer->char (+ r (char->integer #\0))))
(cond
[(<= i 0)
(loop q (cons d digits) i)]
[else
(string-set! str (- i 1) d)
(loop q '() (- i 1))])])))]))
(module+ test
(require rackunit)
(check-equal? (number->string* 1234567890987654321)
(number->string 1234567890987654321))
(for ([x (in-range 1000)])
(check-equal? (number->string* x )
(number->string x))))
(define iterations 1000000)
(define number-to-convert 123)
(collect-garbage)
(time
(for ([x (in-range iterations)])
(number->string 100)))
(collect-garbage)
(time
(for ([x (in-range iterations)])
(number->string* number-to-convert)))
--
You received this message because you are subscribed to the Google Groups
"Racket Users" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
For more options, visit https://groups.google.com/d/optout.