lameduck
lameduck

Reputation: 35

count elements from within a nested list in scheme

I am trying to count elements from within a nested list in scheme, and rank them in order of frequency. For example I have a listP which looks like this '((1 3 6)(1 4 7)(1 5 8)(2 5 7)) and I want scheme to tell me that the order of frequency of the elements is (1 5 7 2 3 4 6 8). Actually I just need the three most frequent, so (1 5 7).

I can't find a function that will find the most frequent element, then get the next most frequent, etc. I have tried max, min, map, length and count but couldn't get anything working at all.

I hope someone can point me in the direction of the function I need. I'm happy to play around with the code once I know what function/s I can use, but this has me beat right now. Thanks!

Upvotes: 1

Views: 1189

Answers (1)

Óscar López
Óscar López

Reputation: 235984

This looks like a job for @ChrisJester-Young's bagify. Here's one possible solution, tested in Racket and using Chris' third implementation of bagify:

(define (frequency lst)
  (map car
       (sort (hash->list (bagify (append* lst)))
             (lambda (x y) (> (cdr x) (cdr y))))))

(frequency '((1 3 6) (1 4 7) (1 5 8) (2 5 7)))
=> '(1 5 7 2 3 4 6 8)

Upvotes: 1

Related Questions