什麼是你的程序背後的邏輯是什麼?你如何期望它通過從輸入列表中刪除元素來找到mode?你應該計數頻率,而不是:
(define (mode lst)
(if (null? lst)
#f ; edge case: an empty list doesn't have a mode
(let loop ((lst lst) ; list to traverse
(current (car lst)) ; current element in sequence
(counter 0) ; number of times current element appears
(max-current (car lst)) ; the mode
(max-counter 0)) ; number of times the mode appears
(cond ((null? lst) ; the list is finished
(if (> counter max-counter) current max-current))
((= (car lst) current) ; current element equal to previous
(loop (cdr lst) ; add 1 to counter and keep iterating
current
(add1 counter)
max-current
max-counter))
(else ; found a different element, a new sequence starts
(loop (cdr lst)
(car lst) ; update current element
1
(if (> counter max-counter) current max-current)
(max counter max-counter)))))))
它通過保持的每一個元素出現了多少次軌道,返回出現最頻繁的元素 - 因爲根據定義的模式是最經常出現的一組值數據的。我們利用輸入列表被排序的事實,因爲我們知道當前元素與我們遇到的前一個元素不同時,會開始一個新的重複元素序列。
+1更清潔,確實更短! –