[racket] a small programming exercise

From: Joe Marshall (jmarshall at alum.mit.edu)
Date: Thu Oct 14 19:21:54 EDT 2010

Here's an interesting data point.

(define (first-digit-fast-1 n)
 (if (> 10 n)
     n
     (let loop ((i 10)
                (next 100))
       (if (> next n)
           (first-digit-fast (floor (/ n i)))
           (loop next (* i i))))))

This takes about 13 seconds on my work machine.

If I take advantage of the types:

(define (first-digit-fast-2 n)
 (if (and (fixnum? n)
	  (fix:> 10 n))
     n
     (let loop ((i 10)
                (next 100))
       (if (int:> next n)
           (first-digit-fast (int:quotient n i))
           (loop next (int:* i i))))))

This takes about 3 seconds.

I think the culprit is the call to (floor (/ n i))
The division will allocate an unnecessary rational.  The int:quotient
primitive doesn't need to.

I'm pretty sure that Racket has some similar primitives.

-- 
~jrm


Posted on the users mailing list.