Frequency List in Scheme

157 Views Asked by At

I want to write a function for finding how many times each element occurs in a list. For example for the list '(1 1 1 2 2 3 4), 1 occurs thrice, 2 occurs twice, and 3 and 4 both occur once. So the output should be like ((1 3) (2 2) (3 1) (4 1)). Here's the code I wrote:

(define (aa-helper list counter)
  (cond [(null? list) '()]
        [(eq? (car list) (cadr list)) (aa-helper (cdr list) (+ counter 1))]
        [else (cons (car list) counter) (aa-helper (cdr list) 1)]))

(define (aa list)
  (aa-helper list 1))

But I got this error:

cadr: contract violation
  expected: (cons/c any/c pair?)
  given: '(4)
0

There are 0 best solutions below