; sorting without duplicates
(define (partition lt? xs) ; assumes sorted xs
(let loop ((xs xs) (prev #f) (ys (list)) (zs (list)))
(cond ((null? xs) (values (reverse ys) (reverse zs)))
((equal? (car xs) prev)
(loop (cdr xs) prev ys (cons (car xs) zs)))
(else (loop (cdr xs) (car xs) (cons (car xs) ys) zs)))))
(define (sort-dups lt? xs)
(let loop ((xs xs) (zs (list)))
(if (null? xs)
(apply append (reverse zs))
(call-with-values
(lambda () (partition lt? xs))
(lambda (first rest)
(loop rest (cons first zs)))))))
(display (sort-dups < (sort '(2 9 1 5 1 4 9 7 2 1 4) <))) (newline)
(display (sort-dups < (sort '(1 1 1 1 1 1 1 1 1) <))) (newline)
(display (sort-dups < (sort '() <))) (newline)
(display (sort-dups < (sort '(7 3 1 6 2 5 4) <))) (newline)
OyBzb3J0aW5nIHdpdGhvdXQgZHVwbGljYXRlcwoKKGRlZmluZSAocGFydGl0aW9uIGx0PyB4cykgOyBhc3N1bWVzIHNvcnRlZCB4cwogIChsZXQgbG9vcCAoKHhzIHhzKSAocHJldiAjZikgKHlzIChsaXN0KSkgKHpzIChsaXN0KSkpCiAgICAoY29uZCAoKG51bGw/IHhzKSAodmFsdWVzIChyZXZlcnNlIHlzKSAocmV2ZXJzZSB6cykpKQogICAgICAgICAgKChlcXVhbD8gKGNhciB4cykgcHJldikKICAgICAgICAgICAgKGxvb3AgKGNkciB4cykgcHJldiB5cyAoY29ucyAoY2FyIHhzKSB6cykpKQogICAgICAgICAgKGVsc2UgKGxvb3AgKGNkciB4cykgKGNhciB4cykgKGNvbnMgKGNhciB4cykgeXMpIHpzKSkpKSkKICAgICAgICAgIAooZGVmaW5lIChzb3J0LWR1cHMgbHQ/IHhzKQogIChsZXQgbG9vcCAoKHhzIHhzKSAoenMgKGxpc3QpKSkKICAgIChpZiAobnVsbD8geHMpCiAgICAgICAgKGFwcGx5IGFwcGVuZCAocmV2ZXJzZSB6cykpCiAgICAgICAgKGNhbGwtd2l0aC12YWx1ZXMKICAgICAgIC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