球拍:如何在结构列表中的结构字段上应用过滤器 [英] Racket: how to apply filter on a field of a struct in a list of struct

查看:67
本文介绍了球拍:如何在结构列表中的结构字段上应用过滤器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的任务是编写一个函数 inYear,它接受一个名为 year 的数字和一个事件结构列表,并生成一个新列表,其中每个元素都是发生在 year 期间的事件结构.我发现了这个 并尝试在过滤器中定义一个 lambda 函数.请参阅下面的我的事件定义/列表、功能和测试.测试失败并且没有元素被过滤掉,它只返回原始列表.我做错了什么?

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. I found this and tried defining a lambda function within the filter. See my event definitions/list, function and test below. 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))

推荐答案

定义 l1 计算结果为符号列表而不是结构列表.

The definition l1 evaluates to a list of symbols not a list of structs.

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

您可以将定义和测试输出分别转换为(list e1 e2 e3 e4)(list e1 e2 e3).

You can convert the definition and the test output to be (list e1 e2 e3 e4) and (list e1 e2 e3) respectively.

或者,您可以使用类似引用-取消引用的组合,例如:

Alternatively, you can use a quasi-quote-unquote combination like:

`(,e1 ,e2 ,e3 ,e4)

但这对于简单地定义结构列表来说不太惯用.

But this is less idiomatic for simply defining a list of structs.

这篇关于球拍:如何在结构列表中的结构字段上应用过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆