将空列表传递给定义类型:可能吗?

发布于 2024-12-05 03:53:12 字数 236 浏览 0 评论 0原文

菜鸟球拍问题。我在这本书中使用了 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

假扮的天使 2024-12-12 03:53:12

空列表不是数字,因此您拥有的类型定义不会接受它。

您可以使用 (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 of number? to accept either a number or an empty list, but I have no idea why you would want to do that.

猥琐帝 2024-12-12 03:53:12

http://docs.racket-lang.org/plai/plai- 中所述schema.html,define-type 可以采用几种不同的变体。它可以以允许语言本身帮助您编写更安全的代码的方式定义不相交的数据类型。

例如:

#lang plai

(define-type Thingy
 [some (num number?)]
 [none])

与 Thingys 配合使用的代码现在需要系统地处理两种可能的 Thingys 类型。当您使用 type-case 时,它​​会在编译时强制执行此操作:如果它发现您编写的代码没有考虑可能的 Thingy 类型,则会抛出编译时错误。

;; bad-thingy->string: Thingy -> string
(define (bad-thingy->string t)
  (type-case Thingy t
    [some (n) (number->string n)]))

这会产生以下编译时错误:

type-case: syntax error; probable cause: you did not include a case for the none variant, or no else-branch was present in: (type-case Thingy t (some (n) (number-> string n)))

没错:代码没有考虑到 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:

#lang plai

(define-type Thingy
 [some (num number?)]
 [none])

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.

;; bad-thingy->string: Thingy -> string
(define (bad-thingy->string t)
  (type-case Thingy t
    [some (n) (number->string n)]))

This gives the following compile-time error:

type-case: syntax error; probable cause: you did not include a case for the none variant, or no else-branch was present in: (type-case Thingy t (some (n) (number-> string n)))

And that's right: the code has not accounted for the case of none.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文