lumbda/examples/mergesort.lsp
russell@unturf.com 1326e8a106 Add peephole optimizer, --help, examples, README update
- Peephole optimizer: eliminates VOID+POP pairs, JUMP-to-next-instruction.
  Adjusts jump targets after dead code removal.
- --help/-h and --version/-v flags.
- 4 example programs: fibonacci, generator, mergesort, objects.
- README rewritten: documents bytecode compiler, --fast flag, all features.
- 529 tests green.
2026-04-13 16:56:21 -04:00

27 lines
762 B
Text

;;; mergesort.lsp — functional merge sort
;;; Run: python3 uncommonlisp.py --fast examples/mergesort.lsp
(define (merge a b)
(cond ((null? a) b)
((null? b) a)
((< (car a) (car b))
(cons (car a) (merge (cdr a) b)))
(else
(cons (car b) (merge a (cdr b))))))
(define (split lst)
(let loop ((l lst) (a '()) (b '()))
(if (null? l)
(list a b)
(loop (cdr l) b (cons (car l) a)))))
(define (msort lst)
(if (or (null? lst) (null? (cdr lst)))
lst
(let ((halves (split lst)))
(merge (msort (car halves))
(msort (cadr halves))))))
(define data (reverse (iota 20)))
(display "Input: ") (display data) (newline)
(display "Sorted: ") (display (msort data)) (newline)