Jason
Jason

Reputation: 21

Racket List Questio

Does anyone know how to return a number of specific elements in a list?

Example: given

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

Returns the numbers of 'a: 5

numbers of 'b: 3

Upvotes: 1

Views: 39

Answers (2)

Jason
Jason

Reputation: 21

I somewhat managed to find the answer, so here's the function definition:

(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))])]))

Upvotes: 1

Sylwester
Sylwester

Reputation: 48765

You count them. You make a procedure that takes a list and what you want to search for and you iterate that list while keeping a count and when you reach the end you return that value.

A skeleton for a simple recursive solution:

(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))

Or you can use 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))

There are probably 10 more ways I could do it, but the first is the most educational and the second the most common way I would do it. Some tests:

(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

Upvotes: 1

Related Questions