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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With