scheme - 如何在 Racket 列表中进行分配

标签 scheme lisp racket

例如,我有一个 6 位数字的列表(1 2 3 4 5 6)。选择一个数字时,它会将其值(+1)分配给它后面的数字:

'(1 2 3 4 5 6) 我选择第 4 个数字,它是 4。

然后程序:

4-1 & 5+1
3-1 & 6+1
2-1 & 1+1
1-1 & 2+1

因为一旦他在 6 点做了,回到列表的开头继续分配自己。 当起始值达到0时停止

我已经有了选择号码的功能,但我不知道这样的分布。

希望已经很清楚了,

非常感谢

最佳答案

有很多方法可以完成您想要做的事情!一种方法是使用“循环列表”。在列表中,每个元素还有一个指向下一个元素的指针。在循环列表中,最后一个元素指向第一个元素,这样您就可以在循环遍历列表时一直环绕!

编写我们自己的循环列表实现并不太难,但幸运的是循环列表可以通过 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 函数可以完成这项工作,但正如我所说,有很多很多方法可以做到这一点。我强烈建议您研究上面的代码并理解它 - 通过少量的努力,您应该能够发现一些远远优于上面的解决方案。祝你好运!

编辑:在评论中,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+).

关于scheme - 如何在 Racket 列表中进行分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53760621/

相关文章:

file-io - 在 Lisp 中保存到文件

regex - 列表到 Racket 中的字符串

scheme - 如何比较 Racket 中的部分字符串匹配?

clojure 解释器中的 Java 样式 FOR 循环?

scheme - 规避 SCHEME 中的 EVAL

scheme - 简化递归函数语法的宏

macros - 宏参数的解构是 "really needed"吗?

emacs - 从 emacs 运行方案

f# - 如果您已经了解 LISP,为什么还要学习 F#?

scheme - 有没有办法在列表中没有列表的情况下进行打印?