[英]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. 然后,我想获取给定name1的name2或name3的值。
One way would be to write 2 functions 一种方法是编写2个函数
(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. 在列表中循环查找其name1与name1 arg匹配的结构,并返回我们想要的属性。
But these 2 functions are basically the same other than one accesses name2, the other accesses name3. 但是这两个功能基本上是相同的,除了一个访问name2,另一个访问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)? 有没有一种更好的方法可以通过单个函数检索name2 / name3(或其他方法)?
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. 我认为更好的方法是先使用库函数查找具有匹配name1
字段的项目,然后提取所需的字段。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.