2017-08-11 64 views
1

我有一个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)  
) 

当我在计划shell中运行上述定义时,一切正常。我可以正确构建point类型。然而,当我尝试构建cpoint类型如下:

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

我收到以下错误:

; ...rfi/9/record.rkt:100:28: arity mismatch;; the expected number of arguments does not match the given number; expected: 1; given: 3; [,bt for context]

我因为cpoint以为是point孩子,它应该接受的参数为point在其构造函数中键入。

我该如何做这项工作?

P.S我是Scheme的新手。

回答

1

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

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

这样的访问者来获得xycpointpoint是不同的。有家长

在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 

您已经标记了球拍,如果你使用的是默认语言,#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)