【问题标题】:Calculating the length of a certain item using map and filter使用地图和过滤器计算某个项目的长度
【发布时间】:2019-11-03 23:20:12
【问题描述】:

我使用 map 和 filter 来计算 Dr.Racket 中三元组列表中某些项目的长度。我想返回一个项目在我的三元组列表中重复的次数。但是,我的代码返回的是三元组的实际长度,而不是项目重复的次数。

 (define (countStatus lst item)
      (map length (filter(lambda (x) (not(equal? x item))) lst)))

 (define lst '((joe  21  “employed”)  ( ann 19 “unemployed”)  (sue 18 “employed” ) ) )

下面的过程应该返回 2,而是返回三元组的长度。

> (countStatus lst "employed")
'(3 3 3)

【问题讨论】:

    标签: scheme racket


    【解决方案1】:

    考虑xfilter 的参数中是什么。它是lst 的一个元素,这意味着它可以是'(joe 21 "employed")'(ann 19 "unemployed")'(sue 18 "employed")

    这些元素都不等于item,即"employed"。因此,与其检查整个元素是否相等,不如检查元素状态是否相等。像这样的:

    ;; Example: (get-status '(joe 21 "employed")) = "employed"
    (define (get-status x) (third x))
    

    那么过滤的谓词应该检查状态是否等于item:

    (lambda (x) (equal? (get-status x) item))
    

    注意它如何使用get-status,以及它如何在等式周围使用not

    使用此谓词过滤后,您可以使用length 代替map length

    ;; Example: (get-status '(joe 21 "employed")) = "employed"
    (define (get-status x) (third x))
    
    (define (countStatus lst item)
      (length (filter (lambda (x) (equal? (get-status x) item)) lst)))
    
    (define lst '((joe 21 "employed") (ann 19 "unemployed") (sue 18 "employed")))
    

    根据这些定义,您会得到如您所愿的2

    > (countStatus lst "employed")
    2
    

    【讨论】:

    • 我尝试使用 cddr x 获取第三个元素,但也没有成功。不过感谢您的解决方案。
    猜你喜欢
    • 1970-01-01
    • 2014-11-23
    • 1970-01-01
    • 2015-07-06
    • 2019-06-09
    • 1970-01-01
    • 2015-10-14
    • 1970-01-01
    • 2018-10-03
    相关资源
    最近更新 更多