【问题标题】:Taking a value and passing it through a list of structures and returning a list that has the corresponding value获取一个值并将其传递给结构列表并返回一个具有相应值的列表
【发布时间】:2020-08-11 19:48:46
【问题描述】:

我正在尝试编写一个函数,该函数需要一年的时间和一个结构列表(定义为事件)作为输入并输出相应的结构。

(define-struct incident (name day mon yr)#:transparent)

(define cake (make-incident "cake" 15 "Apr" 2015))
(define Graduation (make-incident "graduation" 2 "Mar" 2017))

    (define (incidentYr yr aList)
  (foldl
   (lambda (x y) (if (equal? (incident-yr x) yr) (append x y) y))
   '()  aList))

(check-expect (incidentYr 2015 (list (incident "cake" 29 "Apr" 2015) (incident "graduation" 7 "Mar" 2017))) (list (incident "cake" 29 "Apr" 2015)))

但我得到的错误是:

    check-expect encountered the following error instead of the expected value, (list (incident "cake" 29 "Apr" 2015)). 
   :: append: expects a list, given (incident "cake" 29 "Apr" 2015)

好像没用。

【问题讨论】:

    标签: list struct lambda racket matching


    【解决方案1】:

    在 foldl 的 lambda 中,将 (append x y) 更改为 (append (list x) y)。也可以改成(cons x y)

    更自然的解决方案是使用过滤器而不是折叠:

    (filter (λ (x) (= (incident-yr x) yr)) aList)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-09
      • 1970-01-01
      • 2017-09-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多