简体   繁体   中英

Getters for struct fields in a list

I define a struct like this

(struct anobject name1 name2 name3)

I create lists containing these structs

(define list1 (list (anobject name1a name2a name3a) 
                    (anobject name1b name2b name3b)))

I then would like get the value of name2 or name3 given name1.

One way would be to write 2 functions

(define (get-name2 name1)
    ...)

(define (get-name3 name1)
   ...)

that loops through the list looking for the struct whose name1 matches the name1 arg and return the property we want.

But these 2 functions are basically the same other than one accesses name2, the other accesses name3. If I add more fields I will have to add more functions.

Is there a better way of retrieving name2/name3 with a single function (or some other way)?

I think a better way is to first find the item with the matching name1 field using a library function, then extract the field you want.
You can pass the accessor function as a parameter so you only need one function for this.

Example in Racket, but it shouldn't be too hard to adapt to "your" Scheme:

(require srfi/1)  ; For 'find'

(struct anobject (name1 name2 name3))

(define (lookup n1 field ls)
  (let ((r (find (lambda (x) (equal? (anobject-name1 x) n1)) ls)))
    (and r (field r))))

Example of use:

> (define l1 (list (anobject "name1a" "name2a" "name3a") 
                   (anobject "name1b" "name2b" "name3b")))
> (lookup "name1b" anobject-name2 l1)
"name2b"
> (lookup "name1b" anobject-name3 l1)
"name3b"
> (lookup "name1c" anobject-name3 l1)
#f

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM