带有一些值的子结构

时间:2019-05-05 03:34:33

标签: racket

假设我有一个这样的结构:

(struct house (bedrooms bathrooms address price))

如何为具有3间卧室和2间浴室的房屋创建子结构?

(struct 3-2-house house
   ; ???
   ; somehow fill in bedrooms=3 and bathrooms=2
   ; ???
)

(define house-on-apple-street (3-2-house "123 apple street" 100000))

这里似乎需要使用#:auto,但尚不清楚如何将#:auto应用于从父结构继承的字段...

谢谢!

1 个答案:

答案 0 :(得分:-1)

定义结构时,可以通过make-structname创建结构。 定义结构后,您可以使用选择器。

;;; struct name is house
(define-struct house (bedrooms bathrooms label address price))
;;; selector
;;; house-bedrooms house-bathrooms ... house-price

;;; make struct
(define house-on-apple-street (make-house 3 2 "123 apple street" (list 1 2 3) 100000))

(struct? house-on-apple-street)

您可以在struct(家族树)中构建struct

(define-struct house-tree (neighbor1 neighbor2 bedrooms bathrooms price))
(define example
  (make-house-tree empty
                   (make-house-tree empty empty 1 1 100)
                   2 3 200))
(struct? example)

;;; selector
(house-tree-neighbor2 example)