#lang racket (provide 2nd-max) ;; ------------------------------------------------------------------- ;; A functional solution, "Code Golf"-style: one-line! ;; The downside is that it's O(n log n), ;; because it does more work than we need. (define (2nd-max lon) (second (sort lon >))) ;; ------------------------------------------------------------------- ;; A functional solution that doesn't sort. ;; It is O(n), but it makes three passes over the list. ;; ;; (define (2nd-max lon) ;; (apply max ;; (remove (apply max lon) ;; lon))) ;; ------------------------------------------------------------------- (require rackunit) (check-equal? (2nd-max '(6 1 2 -3 9 4 -1 2 8 1 2 4)) 8) (check-equal? (2nd-max '(2 3 8 6 6 75 38 3 2)) 38) (check-equal? (2nd-max '(2 3)) 2) (check-equal? (2nd-max '(2 -1)) -1) ;; -------------------------------------------------------------------