开发者

Passing an empty list to a defined-type: possible?

开发者 https://www.devze.com 2023-04-05 23:16 出处:网络
A rookie Racket question. I\'m using Krishnamurthi\'s PLAI textbook for this one, and the associated Racket programming language.

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:

(def开发者_JAVA技巧ine-type Thingy
 [thingy (num number?)])

So, is there any circumstance at all under which I could get this thingy to accept an empty list '() ?


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号