如何在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