2 ms·
> When I need to change the inputs or outputs of a function, I have no idea if I've done it correctly or not; due to the lack of type checking. Well, the good
by lispm 10y ago
> When I need to change the inputs or outputs of a function, I have no idea if I've done it correctly or not; due to the lack of type checking.
Well, the good news is Common Lisp has runtime types and some implementations even support limited forms of compile time checking.
The Common Lisp Object System allows you to use classes.
One then gets nice runtime errors.
CL-USER> (defmethod add ((a number) (b number)) (+ a b))
#<STANDARD-METHOD COMMON-LISP-USER::ADD (NUMBER NUMBER) {1003ECEF53}>
CL-USER> (defmethod add ((a string) (b string)) (concatenate 'string a b))
#<STANDARD-METHOD COMMON-LISP-USER::ADD (STRING STRING) {1003FDC323}>
This works then:
CL-USER> (add 1 2)
3
Now this will get a runtime error, because there is no method for these arguments:
CL-USER> (add "1" 2)
One can also declare types. For example that something is an integer or a subset of integers...
CL-USER> (defun baz (a)
(flet ((foo (a b)
(declare (integer a b))
(+ a b)))
(foo a "b")))
The SBCL compiler then complains, that above code has a type error:
; in: DEFUN BAZ
; (FOO A "b")
;
; caught WARNING:
; Constant "b" conflicts with its asserted type INTEGER.
; See also:
; The SBCL Manual, Node "Handling of Types"