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