一个菜鸟球拍问题。我使用的是Krishnamurthi的PLAI教科书,以及相关的球拍编程语言。
现在,假设我有一个这样定义的类型:
(define-type Thingy
[thingy (num number?)])那么,有没有什么情况下我可以让这个thingy接受一个空的列表'()呢?
发布于 2011-09-19 10:06:56
空列表不是数字,因此您拥有的类型定义不会接受它。
您可以使用(lambda (x) (or (number? x) (null? x)))而不是number?来接受数字或空列表,但我不知道您为什么要这样做。
发布于 2011-09-21 02:21:51
正如在http://docs.racket-lang.org/plai/plai-scheme.html中所描述的,定义类型可以采用几种不同的变体。它可以以允许语言本身帮助您编写更安全的代码的方式定义不相交的数据类型。
例如:
#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)))这是正确的:代码没有考虑无的情况。
https://stackoverflow.com/questions/7465763
复制相似问题