schemeracketr6rs

Arity mismatch when constructing a child record type


I have a point record type defined as follows:

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

)

Now, I want to extend the point record type and define a new record type as follows:

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

When I run the above to definitions in the scheme shell everything works fine. I can construct point types properly. However, when I try to construct the cpoint type as follows:

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

I get the following error:

; ...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]

I thought since cpoint is child of point, it should have accepted the arguments to the point type in its constructor.

How can I make this work?

P.S I am new to Scheme.


Solution

  • There are no child records in SRFI-9. Thus you need to specify them independently:

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

    Thus the accessors to get x and y for cpoint and point are different.

    Alternatives that has parents

    In R6RS you have (rnrs records syntactic (6)) which is similar to SRFI-9, but not compatible. Your code would look like:

    #!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
    

    You have tagged Racket and if you are using the default language, #lang racket, they have struct:

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

    I added #:transparent since it is the default in R6RS. Of you really want the constructor name to be make-xxx you need to specify it:

    #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)