November 1, 2007

The Most Beautiful Code

In the book Beautiful Code: Leading Programmers Explain How They Think, Andy Oram and Greg Wilson said that Quick Sort is the most beautiful code they had ever seen and coded. Well, they coded in C. Have a look:

(define (filter list get?)
(cond ((null? list) '())
((get? (car list)) (cons (car list) (filter (cdr list) get?)))
(else (filter (cdr list) get?))))

(define (qsort list compare)
(if (null? list)
(let ((pivot (list-ref list (random (length list)))))
(append (qsort (filter list (lambda (x) (< (compare x pivot) 0))) compare)
(filter list (lambda (x) (= (compare x pivot) 0)))
(qsort (filter list (lambda (x) (> (compare x pivot) 0))) compare)))))

Hm, no C code can be better, right?