我是新來的計劃,並且在調試我的代碼時遇到了一些麻煩。計劃拆分操作不起作用
; 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