gpt4 book ai didi

types - 如何在制作实例期间强制检查插槽的类型?

转载 作者:行者123 更新时间:2023-12-04 16:50:37 25 4
gpt4 key购买 nike

假设我有以下类声明:

(defclass foo-class ()
((bar :initarg :bar
:type list)))

当我创建这个类的一个实例时, make-instance不会检查传递的参数是否满足插槽类型。所以,我可以通过这种方式创建“无效”对象:
> (make-instance 'foo-class :bar 'some-symb)
#<FOO-CLASS {102BEC5E83}>

但是,我想看到的是类似于创建结构实例的行为,其中检查类型:
(defstruct foo-struct
(bar nil :type list))

> (make-foo-struct :bar 'some-symb)
;; raises contition:
;;
;; The value
;; SOME-SYMB
;; is not of type
;; LIST
;; when setting slot BAR of structure FOO-STRUCT

有什么办法可以做到这一点?

最佳答案

sanity-clause图书馆昨天刚刚合并了一个功能。

Sanity clause is a data validation/contract library. You might use it for configuration data, validating an api response, or documents from a datastore. In a dynamically typed langauge, it helps you define clearly defined areas of doubt and uncertainty. We should love our users, but we should never blindly trust their inputs.

To make use of it, you define schemas, which can be property lists with symbols for keys and instances of :class:sanity-clause.field:field


所以:
(defclass person ()
((favorite-dog :type symbol
:field-type :member
:members (:wedge :walter)
:initarg :favorite-dog
:required t)
(age :type (integer 0)
:initarg :age
:required t)
(potato :type string
:initarg :potato
:required t))
(:metaclass sanity-clause.metaclass:validated-metaclass))

;; bad dog:
(make-instance 'person :favorite-dog :nope)
; Evaluation aborted on Error converting value for field #<MEMBER-FIELD {1004BFA973}>:
Value "NOPE" couldn't be found in set (WEDGE WALTER)

;; bad age:
(make-instance 'person :age -1 :favorite-dog :walter)
; Evaluation aborted on Error validating value -1 in field #<INTEGER-FIELD {1004BFF103}>:
* Value -1 didn't satisfy condition "must be larger than 0"

;; missing potato:
(make-instance 'person :age 7 :favorite-dog :walter)
; Evaluation aborted on A value for field POTATO is required but none was provided..

;; all OK:
(make-instance 'person :age 1 :favorite-dog :walter :potato "patate")
#<PERSON {10060371E3}>

关于types - 如何在制作实例期间强制检查插槽的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51723992/

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