gpt4 book ai didi

lisp - 在 Lisp 中,你能否构造一个 `check-type`,如果该值不是包含所有整数键和值的哈希表,它会抛出错误?

转载 作者:行者123 更新时间:2023-12-04 22:34:17 24 4
gpt4 key购买 nike

假设我有一个函数:

(defun distribution-to-list (distribution)
(check-type distribution hash-table)
(loop for key being each hash-key of distribution
using (hash-value value) nconc (loop repeat value collect key)))

我想确保至少传入的哈希表的所有值都是整数,因为我正在使用它们将值重复到一个大列表中。有没有办法在内部循环之前使用 check-type 来做到这一点?或者让内部循环宏在尝试 repeat 字符串时抛出类型错误是否足够好? (或任何非整数类型)

最佳答案

如果您可以编写一个函数来检查某个值是否可接受,那么您可以使用 satisfies构造类型说明符,例如 (satisfies is-acceptable)。例如,

(defun all-integer-keys-p (ht)
(loop for k being each hash-key in ht
always (integerp k)))

(let ((h (make-hash-table)))
;; when the table contains only integer
;; keys, we're fine
(setf (gethash 1 h) 'foo
(gethash 2 h) 'bar)
(check-type h (satisfies all-integer-keys-p))

;; but a non-integer key will lead to an
;; error from CHECK-TYPE
(setf (gethash 'three h) 'baz)
(check-type h (satisfies all-integer-keys-p)))

deftype ,您可以将类型定义为 (satisfies all-integer-keys-p) 的简写,您可能会发现它更具可读性:

(deftype all-integer-key-hash-table ()
`(satisfies all-integer-keys-p))

(let ((h (make-hash-table)))
(setf (gethash 1 h) 'foo
(gethash 2 h) 'bar)
(check-type h all-integer-key-hash-table)

(setf (gethash 'three h) 'baz)
(check-type h all-integer-key-hash-table))

关于lisp - 在 Lisp 中,你能否构造一个 `check-type`,如果该值不是包含所有整数键和值的哈希表,它会抛出错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72470575/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com