元数不匹配构建子记录类型
问题描述:
我有一个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的新手。
答
备选项有
SRFI-9中没有子记录。因此,你需要独立指定它们:
(define-record-type cpoint
(make-cpoint x y color)
cpoint?
(x cpoint-x)
(y cpoint-y)
(color cpoint-color))
这样的访问者来获得x
和y
为cpoint
和point
是不同的。有家长
在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)