我是新来的计划,并且在调试我的代码时遇到了一些麻烦。计划拆分操作不起作用
; returns number of elements in a list
(define (length L)
(cond ((null? L) 0)
(else (+ (length (cdr L)) 1))))
; split the list in half:
; returns ((first half)(second half))
(define (split L)
(cond
((= (length L) 0) (list L L))
((= (length L) 1) (list L '()))
(else
(list (sublist L 1 (/ (length L) 2) 1)
(sublist L (+ (/ (length L) 2) 1) (length L) 1)))))
; extract elements start to end into a list
(define (sublist L start end counter)
(cond ((null? L) L)
((< counter start) (sublist (cdr L) start end (+ counter 1)))
((> counter end) '())
(else (cons (car L) (sublist (cdr L) start end (+ counter 1))))))
对我来说,这感觉就像它将一个列表分成两个子列表。可能有更简单的方法来做到这一点,所以我很抱歉,如果这看起来很麻烦。
反正结果:
Expected: (split '(1 2 3 4 5)) = ('(1 2) '(3 4 5))
Actual: (split '(1 2 3 4 5)) = ('(1 2) '(4 5))
很明显的是,length
或split
正在失去的中间值,但我一次又一次的检查,它似乎失去的中间值。这似乎是一个简单的解决办法是摆脱(+ (/ (length L) 2) 1)
的(+ 1)
,但这似乎直觉上我,因为:
Assume L = '(1 2 3 4 5), (/ (length L) 2) = 2, and (+ (/ (length L) 2) 1) = 3
(sublist L 1 (2) 1) = '(1 2)
(sublist L (3) 5 1) = '(3 4 5)
** I put parens around the 2 and 3 to indicate that they were length calculations.
显然,我想提出的假设是错误的,或者我忽视的东西微不足道。
在此先感谢!
对于算法来说,这是一个很酷的名字,我很难与你认真的事实相提并论;) – d11wtq