[racket] Typed/Racket Runtime Optimized Bounded (Index) Increment Operation

From: Ray Racine (ray.racine at gmail.com)
Date: Mon May 14 18:52:33 EDT 2012

I love seeing all them little green boxes informing me that Typed/Racket
has elided runtime operation.  Some of my recent code is doing a great deal
of  processing (Vectorof Float) with vector-ref / vector-set!.

I'm wondering if there is benefit for some deep in the bowels of the Racket
runtime optimized Index type increment operation, e.g., (: ++ (Index ->

(add1 x) is of type Integer -> Integer, which is optimized as a fixnum
operation.  But it also results in the type contraction from Index to
Integer.  One can assert the index variable back to an Index type, but this
is burdensome as one is commonly in some iterative loop with a vector-ref /
vector-set! calls.  Typed/Racket elides a bounds check, but at the cost of
my code explicitly re-asserting the validity of the Index type after every

(let ((v '#(1 2 3)))
  (let: loop : Void ((idx : Index 0))
    (display (vector-ref v idx))
    (loop (assert (add1 idx) Index?))))

I'm robbing Peter to pay Paul here.  The vector-ref bounds check is elided
but I'm paying for this pleasure with explicit checks on the index in every

[Aside: Which is more performant?  Eliding the bounds check or avoiding the
Index? check and using Integer for the indexing variable and letting the
vector-ref impl bounds check the vector-ref for me.  I'd guess the latter.]

I realize there is no free lunch here and somewhere a tax / toll must be
paid.    So I'm thinking (of limited utility to this special case of
indexing, but common enough nonetheless) of a dedicated Racket runtime
operator that optimizes an increment with bounds (Index) check operation.
Say '++' or 'inc1' of type (Index -> Index) which happily throws a runtime
exception if the variable overflows the Index type size.

Then the following happens:

(let ((v '#(1 2 3)))
  (let: loop : Void ((idx : Index 0))
    (display (vector-ref v idx))
    (loop (++ idx))))

And Typed/Racket will show happy Green Boxes for a runtime optimized Index
increment and an elided bounds check in the vector-ref.

Obviously this not a super critical thing.   I don't know if it involves a
couple of bit-mask operations in the runtime or involves rewriting the
entire numeric tower.

Since I'm asking .... more ideally I'd like the Racket runtime to offer an
optimized Ring Algebra on the set of Index type values for the
multiplication and addition operations.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.racket-lang.org/users/archive/attachments/20120514/3ee462fe/attachment.html>

Posted on the users mailing list.