如何在if/else中寫入多個表達式在球拍/方案中?
那麼這不是真正的問題。問題是「如何使用球拍建立滾動窗口程序?」。無論如何,看起來你可能來自另一種編程語言。處理鏈表首先可能有點棘手。但請記住,要計算列表的長度,您必須遍歷整個列表。所以在這裏使用length
是一個反模式。
相反,我會建議您在rolling-window
過程中創建一個aux
iliary過程,在遍歷列表時構建窗口。這樣您就不必浪費迭代計算列表中的元素。
然後,如果您的aux
過程返回並且爲空窗口,那麼您知道您已完成計算給定輸入列表的窗口。
(define (rolling-window n xs)
(define (aux n xs)
(let aux-loop ([n n] [xs xs] [k identity])
(cond [(= n 0) (k empty)] ;; done building sublist, return sublist
[(empty? xs) empty] ;; reached end of xs before n = 0, return empty window
[else (aux-loop (sub1 n) (cdr xs) (λ (rest) (k (cons (car xs) rest))))]))) ;; continue building sublist
(let loop ([xs xs] [window (aux n xs)] [k identity])
(cond ([empty? window] (k empty)) ;; empty window, done
([empty? xs] (k empty)) ;; empty input list, done
(else (loop (cdr xs) (aux n (cdr xs)) (λ (rest) (k (cons window rest)))))))) ;; continue building sublists
(rolling-window 3 '(1 2 3 4 5 6))
;; => '((1 2 3) (2 3 4) (3 4 5) (4 5 6))
它適用於空窗
(rolling-window 0 '(1 2 3 4 5 6))
;; => '()
而空列表太
(rolling-window 3 '())
;; => '()
https://docs.racket-lang.org/reference/if.html – coredump
使用'cond'。或者,用'begin'或'let'封裝分支,但使用'cond'可能更容易。 –
(取l尺寸)(滾動窗口(cdr l)尺寸) 應該在else部分不需要第三個替代方案 – X10D