【问题标题】:Accessing structure sub-type fields in Scheme and Racket访问 Scheme 和 Racket 中的结构子类型字段
【发布时间】:2011-12-23 20:03:25
【问题描述】:

在球拍中,这给了我一个错误:

(struct point-in-plane  (pos_x pos_y))  
(struct pixel point-in-plane (color))  

(define a-pixel (pixel 1 2 "blue"))  
(pixel-color a-pixel)  
(pixel-pos_x a-pixel) 
(pixel-pos_y a-pixel) 

为了让它工作,我需要将最后两行替换为:

(point-in-plane-pos_x a-pixel) 
(point-in-plane-pos_y a-pixel) 

在 R6RS 中类似

#!r6rs
(import (rnrs))
(define-record-type point (fields x y))
(define-record-type cpoint (parent point) (fields color))
(define blue-point  (make-cpoint 1 2 "blue"))
(write (cpoint-x blue-point))

给出类似的错误。

Scheme(和 Racket)不允许您访问通过以下方式在父类中定义的子类型的字段的原因是什么: subtypeID-fieldID 而不是 parenttypeID-fieldID

即在我的情况下,允许我使用 pixel-pos_x 和 pixel-pos_y 。

【问题讨论】:

    标签: scheme racket


    【解决方案1】:

    一个原因是struct 允许您定义具有相同名称字段的子结构。例如:

    (struct base (x y))
    (struct sub base (x y))
    
    (define rec (sub 1 2 3 4))
    (base-x rec) ; => 1
    (sub-x rec)  ; => 3
    

    这是因为结构并不真正了解字段名称。来自Racket documentation:“结构类型的字段本质上是未命名的,尽管名称支持用于错误报告目的。”您必须禁止这种行为才能获得子结构的额外访问器。

    【讨论】:

      【解决方案2】:

      struct 表单的documentation 表示它为给定字段提供了访问器和设置器,但没有说它会自动重新公开父级的现有访问器和设置器输入您期望的额外名称。

      当我处理结构并按名称提取组件时,我经常使用racket/match 库,尤其是struct* 模式匹配器。通常,我必须处理一个结构的多个组件,而匹配器可以很容易地做到这一点。

      【讨论】:

      • 谢谢丹尼尔。如果你手头有一个例子,你可以发给我(到 harryspier@hotmail.com),这对我很有帮助。
      猜你喜欢
      • 1970-01-01
      • 2010-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-06
      • 2016-09-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多