[racket] One accessor for the same fields of different structs?

6 views
Skip to first unread message

Ben Duan

unread,
Nov 25, 2013, 9:20:26 AM11/25/13
to users
Hi All,

If I have several structures, like the following:

    (struct customer (name age foo))
    (struct student (name age bar))

I choose the same representation for the `name` and `age` fields which are `string?` and `natural-number/c`. So I think I could just define a `name` accessor for both `customer-name` and `student-name` to save some typing. I have to define the accesors by hand like:

    (define (name record)
      (cond
        ((customer? record) (customer-name record))
        ((student? record) (student-name record))))
    (define (age record)
      (cond
        ((customer? record) (customer-age record))
        ((student? record) (student-age record))))

1. It's much repetitive work. Is there any built-in way to do these things?
    I think macro can do these. But I'm trying to avoid macros as much as I could, because I don't trust myself in designing macros. 

2. Is it good or bad style to use one accessor for different structs?

Thanks,
Ben

Laurent

unread,
Nov 25, 2013, 9:28:07 AM11/25/13
to Ben Duan, users
No need for a macro here, you simply need to define a common parent struct `person', and derive `customer' and `student' from this struct:

(struct person (name age))
(struct customer person (foo))
(struct student person (bar))

(person-name (customer "Joe" 34 'foo)) ; -> "Joe"

The parent struct name must be given right after the struct name of the child.

Laurent

____________________
  Racket Users list:
  http://lists.racket-lang.org/users


William J. Bowman

unread,
Nov 25, 2013, 9:35:21 AM11/25/13
to Ben Duan, users
Ben,

I'm not sure what problem you're actually trying to solve, but you may want to look at

0) struct super-type http://docs.racket-lang.org/reference/creatingmorestructs.html
1) generic interfaces http://docs.racket-lang.org/reference/struct-generics.html
2) racket objects http://docs.racket-lang.org/reference/mzlib_class.html

--

William J. Bowman
Sent from my tablet device

Matthias Felleisen

unread,
Nov 25, 2013, 11:06:29 AM11/25/13
to William J. Bowman, users

Or match and define-match and define/match if you wish to avoid writing selectors.
Reply all
Reply to author
Forward
0 new messages