使用累积递归查找drracket中的最长赢款
假设使用累积递归查找drracket中的最长赢款,racket,Racket,假设(列出'win'loss'win'win'win'loss'win'win'win)并产生最长的胜利,即3。使用累积递归。我所做的如下: (define (fun list) (local [(define (helper los accu1 accu2) (cond [(empty? los) (length accu2)] [else (cond [(equal? (first lo
(列出'win'loss'win'win'win'loss'win'win'win)
并产生最长的胜利,即3。使用累积递归。我所做的如下:
(define (fun list)
(local
[(define (helper los accu1 accu2)
(cond
[(empty? los) (length accu2)]
[else
(cond
[(equal? (first los) 'loss)
(helper (rest los) 0 accu2)]
[else
(helper (rest los) 0 (cons (first los) accu2))])]))]
(helper list empty empty)))
问题是,当我在列表中失败时,我不知道该怎么办,我的函数只计算所有赢款,而不是最长赢款。请有人帮忙:)。这可能是您想要的:
(define (fun lst)
(define (helper lst current longest)
(cond
[(empty? lst) (max current longest)]
[(equal? (first lst) 'win) (helper (rest lst) (add1 current) longest)]
[else (helper (rest lst) 0 (max current longest))]))
(helper lst 0 0))
然后
关键是您需要2个变量;一个表示当前连续的'win
符号数,另一个表示先前最高的连续数。不需要创建中间列表,计数器就足够了
> (fun (list 'win 'loss 'win 'win 'win 'loss 'win 'win))
3