[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: small integers



    Rather than focusing on different integer classes, it's possible to
    cast the issue as one of using different operations.

Short-integer-specific operators were used by most pre-Common Lisp
dialects.  It is a proven way to get efficient code.  Most portable Common
Lisp systems manufacture fixnum-specific operators using macros that insert
all possible (THE FIXNUM ...) declarations.

My main objection to relying on special <short-integer> operations (or
Common Lisp output type declarations) is that it makes it difficult to
write polymorphic arithmetic expressions.  For example, I could write:
    (define quadratic
      (method (x a b c)
	(+ (* (+ (* x a) b) x) c)))

This function can be used with any kind of number; if inline expanded
to allow specialized compilation it should also be quite efficient.
However, if special operators or output type assertions are required for
short integers, then short-integer uses will not be efficient.  As Scott
says, having special operators is not very object-oriented.

I also think that type-specific operators have a greater cognitive risk of
introducing bugs.  Since you want the type-specific operation 99.9% of the
time, you get used to always typing it, and somtimes type it when you
shouldn't have.

Another way to look at this is that the more times you have to say
<short-integer>, the more chances you have of being wrong.  Since
<extended-integer> is contagious, the error of using a short operation on
extended operands is not possible.

A slightly unrelated example of how you get into trouble with type-specific
operators comes from CLX (the Common Lisp X library.)  Since integers in
system programs are almost always array indices (non-negative short
integers), CLX defines the INDEX type to be a non-negative FIXNUM, and
defines macros INDEX+, INDEX-, etc., which insert THE declarations.
These INDEX operators ended up being always used, too invariably, in fact.
The operands were indeed always small integers, but were not always
non-negative.  

In particular, in a few places, (INDEX- X) was used to negate an integer.
Since most Common Lisp implementations ignore the non-negative part of the
INDEX declaration, this problem was only detected when Python inferred that
X must be 0, and complained that a subsequent comparison made code
unreachable.

  Rob