我有一个6位数的列表’(1 2 3 4 5 6)例如。选择数字时,它会将其值(+1)分配给后面的数字:
’(1 2 3 4 5 6)我选择第4位,它是4位。
该程序 …
有很多方法可以做你想要做的事情!一种方法是使用“循环列表”。在列表中,每个元素还有一个指向下一个元素的指针。在循环列表中,最后一个元素指向第一个元素,因此当您遍历列表时,您只需保持环绕!
编写我们自己的循环列表实现并不是很难,但幸运的是循环列表可以通过 srfi/1 图书馆。使用该库的一种可能实现如下所示:
srfi/1
#lang racket (require srfi/1) ; function we will apply distributively to values in list (define (1+ val) (+ val 1)) (define (distribute function l n) ; we define an inner function so we can take list l ; and convert it to a "circular" list (define (inner-distribute func circular-l n count) (if (> count 0) (cons (func (list-ref circular-l n)) (inner-distribute func circular-l (+ n 1) (- count 1))) '())) (inner-distribute function (apply circular-list l) n n)) (distribute 1+ '(1 2 3 4 5 6) 4) ; this returns the list '(6 7 2 3) ; just like you specified in your question!
那 distribute 功能完成工作,但就像我说的,有 很多很多 这样做的方法。我强烈建议您研究上面的代码并理解它 - 只需要少量的努力,您就应该能够发现一些远远优于上述代码的解决方案。祝好运!
distribute
编辑:在评论中OP感觉上面的代码对他们来说有点太多了解。这是另一种方法:
(require srfi/1) ; function we will apply distributively to values in list (define (1+ val) (+ val 1)) (define (distribute func l n) (map (lambda (x) (func (list-ref (apply circular-list l) x))) (range n (+ n n)))) (distribute 1+ '(1 2 3 4 5 6) 4) ; works!
这个解决方案背后的想法是我们制作一个从n到n * 2的数字列表,然后在我们的循环列表中获取每个数字索引的元素并对其应用一个函数(在这种情况下,1 +) 。