I've set up a procedure in scheme that will analyze a list and return the middle index when the list is odd, and the average of the middle 2 values when the list is even. Here's what I have (these ones run perfectly fine by themselves):

(define (median-index-odd lst)
    (define (median-index-iter1 lst times_carred)
        (if (null? lst)
           '()
            (if (= times_carred (/ (+ (length lst) 1) 2)) 
                (list (car lst))            
                (median-index-iter1 (cdr lst) (+ 1 times_carred)))))
                (median-index-iter1 lst 0))

(define (median-index-even lst)
    (define (median-index-iter2 lst times_carred)
        (if (null? lst)
           '()
            (if (= times_carred (/ (length lst) 2)) 
                (list (/ (+ (car lst) (cadr lst)) 2))          
                (median-index-iter2 (cdr lst) (+ 1 times_carred)))))
                (median-index-iter2 lst 0))

Here's the actual procedure, without all the clutter from those helpers.

(define (median lst)
    (if (null? lst) 
       '()
        (if (even? lst) 
            (median-index-even lst)
            (median-index-odd lst))))

However, when I try and run test cases, I get an error:

(display (median '(1 2 2 3 3 3 4 5))) (newline)

The object (1 2 2 3 3 3 4 5), passed as the first argument to integer-remainder, is not the correct type.

EDIT: Okay, yes, I completely overlooked the (even? (length lst)) part. I am currently debugging the helpers right now.

有帮助吗?

解决方案

For starters this line is wrong, a list can not be even:

(if (even? lst)

A list's length, however, is a different matter:

(if (even? (length lst))

Also, in both procedures the comparison for determining if the list's mid point has been reached is wrong, you'll have to tweak this line in both helper procedures, because currently is not working:

(if (= times_carred ...

It'll be simpler if you start times_carred in 1 and change the condition to (>= times_carred (/ (length lst) 2)), the same comparison works for both cases.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top