Common Lisp有DEFTYPE
用于定义新类型。例如:
(defun secondsp (s)
(<= 0 s 59))
(deftype seconds()
'(and number (satisfies secondsp)))
(let ((s 0))
(declare (type seconds s))
(loop
repeat 60 ;should cause an error when S becomes 60
do (incf s)
do (write-char #\.)))
它不会阻止您添加秒和米一起,但:
(deftype meters()
'number)
(let ((s 30)
(m 15))
(declare (type seconds s)
(type meters m))
(+ s m))
;=> 45
你可以创建一个使用CHECK-TYPE
或声明的函数来检查值是一个有效的几秒钟:
;; with CHECK-TYPE and THE
(defun add-seconds (s1 s2)
(check-type s1 seconds)
(check-type s2 seconds)
(the seconds (+ s1 s2)))
;; With declarations
(declaim (ftype (function (seconds seconds) seconds) add-seconds-decl))
(defun add-seconds-decl (s1 s2)
(+ s1 s2))
但是,那只会检查值是有效的秒。它不关心你是否声明该变量是米,因为该函数只传递该值。
(let ((s1 30)
(s2 15)
(m 25))
(declare (type seconds s1 s2)
(type meters m))
(format t "~&S1 + S2 = ~a" (add-seconds-decl s1 s2))
(format t "~&S1 + M = ~a" (add-seconds-decl s1 m)))
;; S1 + S2 = 45
;; S1 + M = 55
如果您想要强制执行秒和米永远不会加在一起,您应该只使用类和对象。
请参阅Gordon S. Novak Jr的[计量单位转换](https://www.cs.utexas.edu/users/novak/units95.html)。 – coredump