【问题标题】:Arity mismatch when constructing a child record type构造子记录类型时的 Arity 不匹配
【发布时间】:2017-08-11 13:16:18
【问题描述】:

我有一个point 记录类型定义如下:

(define-record-type point
    (make-point x y)
    point?
    (x point-x)
    (y point-y)   

)

现在,我想扩展point 记录类型并定义一个新的记录类型,如下所示:

(define-record-type cpoint 
    (make-cpoint color)
    cpoint?
    (color cpoint-color)   
    (parent point)    
)

当我在方案外壳中运行上述定义时,一切正常。我可以正确构造point 类型。但是,当我尝试按如下方式构造 cpoint 类型时:

(define p2 (make-cpoint 8 9 'red))

我收到以下错误:

; ...rfi/9/record.rkt:100:28: 数量不匹配;;预期数量 参数与给定的数字不匹配;预期:1;给定:3; [,bt 表示上下文]

我想既然cpointpoint 的孩子,它应该在其构造函数中接受point 类型的参数。

我怎样才能做到这一点?

P.S 我是 Scheme 的新手。

【问题讨论】:

    标签: scheme racket r6rs


    【解决方案1】:

    SRFI-9 中没有子记录。因此,您需要单独指定它们:

    (define-record-type cpoint 
      (make-cpoint x y color)
      cpoint?
      (x cpoint-x)
      (y cpoint-y)
      (color cpoint-color))
    

    因此,cpointpoint 获取 xy 的访问器是不同的。

    有父母的替代品

    在 R6RS 中有 (rnrs records syntactic (6)),它类似于 SRFI-9,但不兼容。您的代码如下所示:

    #!r6rs
    
    (import (rnrs base)
            (rnrs records syntactic))
    
    (define-record-type (point make-point point?)
      (fields (immutable x point-x)
              (immutable y point-y)))
    
    (define-record-type (cpoint make-cpoint cpoint?)
      (fields (immutable c cpoint-c))
      (parent point))
    
    
    (make-cpoint 4 5 'red) ; ==>  implementation chosen visual representation, perhaps #cpoint-4-5-red
    

    您已标记 Racket,如果您使用默认语言 #lang racket,则他们有 struct

    #lang racket
    
    (struct point (x y) #:transparent) 
    (struct cpoint point (color) #:transparent) 
    
    (cpoint 4 5 'red) ; ==>  (cpoint 4 5 'red)
    

    我添加了#:transparent,因为它是 R6RS 中的默认设置。如果您真的希望构造函数名称为make-xxx,您需要指定它:

    #lang racket
    
    (struct point (x y)
      #:constructor-name make-point
      #:transparent) 
    
    (struct cpoint point (color)
      #:constructor-name make-cpoint
      #:transparent) 
    
    (make-cpoint 4 5 'red) ; ==>  (cpoint 4 5 'red)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-17
      • 1970-01-01
      • 2011-12-28
      • 2011-10-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多