将空列表传递给定义类型:可能吗?
菜鸟球拍问题。我在这本书中使用了 Krishnamurthi 的 PLAI 教科书以及相关的 Racket 编程语言。
现在,假设我有一个这样定义的类型:
(define-type Thingy
[thingy (num number?)])
那么,是否有任何情况下我可以让这个 thingy
接受一个空列表 '()
?
A rookie Racket question. I'm using Krishnamurthi's PLAI textbook for this one, and the associated Racket programming language.
Now, let's say that I have a defined type as such:
(define-type Thingy
[thingy (num number?)])
So, is there any circumstance at all under which I could get this thingy
to accept an empty list '()
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
空列表不是数字,因此您拥有的类型定义不会接受它。
您可以使用
(lambda (x) (or (number? x) (null? x)))
而不是number?
来接受数字或空列表,但我不知道你为什么要这样做。An empty list is not a number, so the type definition you have will not accept it.
You can use
(lambda (x) (or (number? x) (null? x)))
instead ofnumber?
to accept either a number or an empty list, but I have no idea why you would want to do that.如 http://docs.racket-lang.org/plai/plai- 中所述schema.html,define-type 可以采用几种不同的变体。它可以以允许语言本身帮助您编写更安全的代码的方式定义不相交的数据类型。
例如:
与 Thingys 配合使用的代码现在需要系统地处理两种可能的 Thingys 类型。当您使用 type-case 时,它会在编译时强制执行此操作:如果它发现您编写的代码没有考虑可能的 Thingy 类型,则会抛出编译时错误。
这会产生以下编译时错误:
没错:代码没有考虑到 none 的情况。
As described in http://docs.racket-lang.org/plai/plai-scheme.html, define-type can take several different variants. It can define a disjoint datatype in a way that allows the language itself to help you write safer code.
For example:
Code that works with Thingys now need to systematically process the two possible kinds of Thingys. When you use type-case, it will enforce this at compile time: if it sees that you have written code that doesn't account for the possible kinds of Thingy, it'll throw a compile-time error.
This gives the following compile-time error:
And that's right: the code has not accounted for the case of none.