3 ms·
Doing the naive thing in CL without thinking about things like 'efficiency' or 'maintainability': (let ((test-input '((1 "one") (1 "two") (1 "three") (1 "one
by tmtvl 3y ago
Doing the naive thing in CL without thinking about things like 'efficiency' or 'maintainability':
(let ((test-input '((1 "one") (1 "two") (1 "three") (1 "one") (1 "four") (1 "two"))))
(mapcar (lambda (string)
(list (count string test-input :test #'string= :key #'second)
string))
(remove-duplicates (mapcar #'second test-input)
:test #'string= :from-end t)))
I will admit it's not as short as:
v:((1;"one");(1;"two");(1;"three");(1;"one");(1;"four");(1;"two"))
+(#:'=v[;1];?v[;1])
- SeanLuke 3y agoNow you have me thinking about how short I can make that. My revision: (defun doit (elts) (mapcar (lambda (elt) `(,(count elt elts :test 'equal :key 'second) ,elt)) (delete-duplicates (mapcar 'second elts) :test 'equal))))) or maybe (defun doit (elts) (loop for elt in (delete-duplicates (mapcar 'second elts) :test 'equal) collect `(,(count elt elts :test 'equal :key 'second) ,elt)))
- tmtvl 3y agoAs much as Lisp isn't meant for code golf, I think the loop variation could be used as a (rather long) one-liner.
- taeric 3y agoMy naive looked more like: (with apologies on likely messing up spacing in hn.) (let ((in '((1 "one") (1 "two") (1 "three") (1 "one") (1 "four") (1 "two")))) (loop with hash = (make-hash-table :test #'equal) for v in in do (incf (gethash (cadr v) hash 0)) finally (return (loop for key being the hash-keys of hash collect (list (gethash key hash) key)))))