Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using (declare (type ...)) but still have 'safe' functions

Is it possible to use (declare (type ...)) declarations in functions but also perform type-checking on the function arguments, in order to produce faster but still safe code?

For instance,

(defun add (x y)
    (declare (type fixnum x y))
    (the fixnum x y))

when called as (add 1 "a") would result in undefined behaviour, so preferably I'd like to modify it as

(defun add (x y)
    (declare (type fixnum x y))
    (check-type x fixnum)
    (check-type y fixnum)
    (the fixnum x y))

but I worry that the compiler is allowed to assume that the check-type always passes and thus omit the check.

So my question is, is the above example wrong as I expect it, and secondly, is there any common idiom* in use to achieve type-safety with optimised code?

*) I can imagine, for instance, using an optimised lambda and calling that after doing the type-checking, but I wonder if that's the most elegant way.

like image 315
MicroVirus Avatar asked Aug 31 '15 22:08

MicroVirus


1 Answers

You can always check the types first and then enter optimized code:

(defun foo (x)
  (check-type x fixnum)
  (locally
    (declare (fixnum x)
             (optimize (safety 0)))
    x))

The LOCALLY is used for local declarations.

like image 56
Rainer Joswig Avatar answered Sep 18 '22 16:09

Rainer Joswig