On 9/9/10 11:26 AM, Eli Barzilay wrote:
On Sep 9, David Van Horn wrote:
[...] As for the structure of the code as given, I would use helper
functions in place of the `let'. The resulting code will be easier
to read and the helper functions can be tested independently, making
it easier to maintain and improve the likelihood that the whole
program is correct; and correctness and ease of maintenance are
important aspects of style.
Sounds like an overkill in this case, and for most values of
"idiomatic" I'd say that it'd make it less so.
This is what I had in mind. I find this solution easier to read and
reason about. Is it really overkill? Less idiomatic?
#lang racket
(require test-engine/racket-tests)
;; A sample is represented as a non-empty list of real numbers.
;; Sample = [Pair Real [Listof Real]]
(check-expect (median (list 1)) 1)
(check-expect (median (list 1 2)) 3/2)
(check-expect (median (list 1 2 3)) 2)
(check-expect (median (list 3 1 2)) 2)
(check-expect (median (list 3 3 2)) 3)
;; Sample -> Real
(define (median lon)
(median-sorted (sort lon <)
(length lon)))
;; Sample Natural -> Real
;; lon is sorted, (= n (length lon)).
(define (median-sorted lon n)
(cond [(odd? n) (list-ref lon (quotient n 2))]
[else
(mean (list-ref lon (sub1 (quotient n 2)))
(list-ref lon (quotient n 2)))]))
;; Real Real -> Real
(define (mean r1 r2)
(/ (+ r1 r2) 2))
(test)
_________________________________________________
For list-related administrative tasks:
http://lists.racket-lang.org/listinfo/users