• .Re: ANSI Common Lisp, Page 56, Problem 3

    From Robert L.@21:1/5 to All on Thu Mar 3 20:25:20 2022
    On 2016-08-30, Steve Graham <solitary.wanderer52@gmail.com> wrote:
    The problem states:

    Define a function that takes a list and returns a list indicating the number of times each (eql) element appears, sorted from most common
    element to least common

    $ txr
    This is the TXR Lisp interactive listener of TXR 147.
    Use the :quit command or type Ctrl-D on empty line to exit.
    [group-by identity '(a a b a c b c c a a d e)]
    #H(() (e (e)) (d (d)) (a (a a a a a)) (c (c c c)) (b (b b)))
    [hash-update [group-by identity '(a a b a c b c c a a d e)] length]
    #H(() (e 1) (d 1) (a 5) (c 3) (b 2))
    (hash-pairs [hash-update [group-by identity '(a a b a c b c c a a d
    e)] length])
    ((e 1) (d 1) (a 5) (c 3) (b 2))
    [sort (hash-pairs [hash-update [group-by identity '(a a b a c b c c
    a a d e)] length]) > second]
    ((a 5) (c 3) (b 2) (d 1) (e 1))

    Without using a hash-table or mutation.

    Gauche Scheme:

    (use srfi-1) ;; lset-difference

    (define (update-alist alist item)
    (define found (assoc item alist))
    (if found
    (cons (list item (+ 1 (cadr found)))
    (lset-difference (lambda (a b) (equal? (car a) b))
    alist (list item)))
    (cons (list item 1) alist)))

    (define (foo the-list)
    (let go ((xs the-list) (counts '()))
    (if (null? xs)
    (sort counts > cadr)
    (go (cdr xs) (update-alist counts (car xs))))))

    (foo '(a a b a c b c c a a d e))
    ===>
    ((a 5) (c 3) (b 2) (e 1) (d 1))

    --- SoupGate-Win32 v1.05
    * Origin: fsxNet Usenet Gateway (21:1/5)