简体   繁体   English

球拍:如何在结构列表中的结构字段上应用过滤器

[英]Racket: how to apply filter on a field of a struct in a list of struct

My task is to write a function, inYear, which takes a number called year, and a list of event structures and produces a new list where each element is an event structure which occurred during year.我的任务是编写一个 function,inYear,它需要一个称为年份的数字,以及一个事件结构列表并生成一个新列表,其中每个元素都是一年中发生的事件结构。 I found this and tried defining a lambda function within the filter.我发现了这个并尝试在过滤器中定义一个 lambda function 。 See my event definitions/list, function and test below.请参阅我的事件定义/列表 function 并在下面进行测试。 The test fails and no elements get filtered out, it just returns the original list.测试失败并且没有元素被过滤掉,它只返回原始列表。 What am I doing wrong?我究竟做错了什么?

(struct event (name day month year xlocation ylocation) #:transparent)

(define e1 (event "new years" 1 "Jan" 2021 0 0))
(define e2 (event "valentines" 14 "Feb" 2021 2 2))
(define e3 (event "my birthday" 6 "Mar" 2021 10 10))
(define e4 (event "tyler's birthday" 10 "Sep" 2020 20 20))
(define l1 '(e1 e2 e3 e4))

(define (inYear year events)
  (filter (lambda (e) (equal? (event-year e) year)) events))

(check-expect (inYear 2021 l1) '(e1 e2 e3))

The definition l1 evaluates to a list of symbols not a list of structs.定义l1计算为符号列表而不是结构列表。

'(e1 e2 e3 e4) = (list 'e1 'e2 'e3 'e4)

You can convert the definition and the test output to be (list e1 e2 e3 e4) and (list e1 e2 e3) respectively.您可以将定义和测试 output 分别转换为(list e1 e2 e3 e4)(list e1 e2 e3)

Alternatively, you can use a quasi-quote-unquote combination like:或者,您可以使用 quasi-quote-unquote 组合,例如:

`(,e1 ,e2 ,e3 ,e4)

But this is less idiomatic for simply defining a list of structs.但这对于简单地定义结构列表来说并不那么惯用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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