scheme - Getters for struct fields in a list -


i define struct this

(struct anobject name1 name2 name3) 

i create lists containing these structs

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

i value of name2 or name3 given name1.

one way write 2 functions

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

that loops through list looking struct name1 matches name1 arg , return property want.

but these 2 functions same other 1 accesses name2, other accesses name3. if add more fields have add more functions.

is there better way of retrieving name2/name3 single function (or other way)?

i think better way first find item matching name1 field using library function, extract field want.
can pass accessor function parameter need 1 function this.

example in racket, shouldn't hard adapt "your" scheme:

(require srfi/1)  ; '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 

Comments

Popular posts from this blog

java - Suppress Jboss version details from HTTP error response -

gridview - Yii2 DataPorivider $totalSum for a column -

Sass watch command compiles .scss files before full sftp upload -