球拍列表问题

时间:2018-06-08 20:36:09

标签: racket

有谁知道如何在列表中返回一些特定元素?

示例:给出

(list 'a 'a 'a 'a 'a 'b 'b 'b)

返回'a: 5

的数字

'b: 3

的数量

2 个答案:

答案 0 :(得分:1)

你算他们。您创建一个过程,该过程采用列表和您要搜索的内容,并在保持计数的同时迭代该列表,当您到达结束时,您将返回该值。

简单递归解决方案的框架:

(define (count-element element lst)
  (define (helper lst count)
    (cond ((empty? lst) count)
          ((equal? element <first element>) <recurse whith cdr and increasing count>)
          (else <recurse with cdr>)))
  (helper lst 0))

或者您可以使用foldl

(define (count-element element lst)
  (foldl (lambda (e count)
           (if <e is the same as element>
               <return 1 more than count>
               <return count>))
         0
         lst))

我可能还有10种方法可以做到这一点,但第一种方式是最具教育意义,第二种方式是我最常用的方式。 一些测试:

(define test '(a a a a a b b b))

(count-element 'b '()) ; ==> 0
(count-element 'e test) ; ==> 0 
(count-element 'a test) ; ==> 5
(count-element 'b test) ; ==> 3

答案 1 :(得分:1)

我有点设法找到答案,所以这里是函数定义:

(define (number-of s L)
  (cond
    [(empty? L) 0]
    [else (cond [(eq? s (first L)) (+ 1 (number-of s (rest L)))]
                [else (number-of s (rest L))])]))
相关问题