我使用地图和过滤器来计算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)
考虑x
的参数中filter
的含义。它是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))
然后,用于过滤的谓词应检查状态是否等于该项目:
(lambda (x) (equal? (get-status x) item))
注意它如何使用get-status
,以及它如何not在等号周围使用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