elegant way to count items

后端 未结 9 1999
感情败类
感情败类 2020-12-10 15:29

I have a list shaped like this:

  \'((\"Alpha\" .  1538)
    (\"Beta\"  .  8036)
    (\"Gamma\" .  8990)
    (\"Beta\"  .  10052)
    (\"Alpha\" .  12837)
           


        
9条回答
  •  情书的邮戳
    2020-12-10 15:39

    Using high-order functions sort and reduce.

    First sorting (using string<) then reducing (counting consecutive string= values in cons cells):

    (reduce (lambda (r e)
              (if (and r (string= (caar r) e))
                  (cons
                   (cons (caar r) (1+ (cdar r)))
                   (cdr r))
                (cons (cons e  1) r)))
            (sort (mapcar 'car alist) 'string<)
            :initial-value nil)
    

提交回复
热议问题