简体   繁体   English

如何使用Scheme将列表的第一个元素移动到列表的末尾?

[英]How to move the first element of a list to the end of the list using Scheme?

I've been looking over this and I can add "something" to the end of the list, but the issue I'm arriving at is adding, specifically, the first element of a list to the end of that same list. 我一直在寻找,可以在列表的末尾添加“内容”,但是我要解决的问题是,将列表的第一个元素添加到同一列表的末尾。

For example: 例如:

{1, 2, 3, 4} becomes {1, 2, 3, 4, 1}. {1,2,3,4}变为{1,2,3,4,1}。

Here is the code that I'm having problems with: 这是我遇到问题的代码:

(define (copy-first-to-end lst)
  (cond [(empty? lst)   
         (cons (first lst) empty)]       
        [else  (cons (first lst)    
               (copy-first-to-end (rest lst)))])) 

The issue with this code is that, for the empty? 这段代码的问题在于,是否为空? condition, the answer calls (first lst) but because it is recursive, the first element of this list is empty. 条件,答案会调用(第一个lst),但由于它是递归的,因此此列表的第一个元素为空。 Since scheme is dynamically typed, I can't store the first element anywhere (at least I don't think I can). 由于scheme是动态类型的,因此我无法将第一个元素存储在任何地方(至少我不认为可以)。

How can I get this to work, using only the basic list functions? 仅使用基本列表功能,如何使它起作用? (eg, cons, cons?, empty? first, last, rest) (例如,缺点,缺点?,为空?首先,最后,休息)

You can use closures to store anything you want. 您可以使用闭包存储所需的任何内容。

Here's the solution I wrote, with a few details removed to give you some space to think. 这是我编写的解决方案,其中删除了一些细节,为您提供了一些思考的空间。 :-) :-)

(define (copy-first-to-end lst)
  (define top ???)
  (define (inner lst)
    (if (null? lst) ???
        (cons ??? (inner ???))))
  (inner ???))

In this case, inner is a closure that, among other things, has access to the top variable (which you will use to stash your value of interest). 在这种情况下, inner是一个闭包,除其他外,它可以访问top变量(您将使用该变量来存储您的兴趣值)。

So you are essentially trying to write your own implementation of the append function, with the special case that you will be appending a list containing the first s-expression from the list. 因此,您实际上是在尝试编写自己的append函数实现,特殊情况是您将追加一个包含该列表中第一个s表达式的列表。 Your problem is that you can't cons a flat list into a flat list and get a single flat list as a result. 您的问题是您无法将一个平面列表限制为一个平面列表,从而无法获得一个平面列表。 The only way to do this with cons is to break the first list down into its constituent s-expressions and then cons them into the second list in reverse order . 使用cons的唯一方法是将第一个列表分解成其组成的s-表达式,然后以相反的顺序将它们限制在第二个列表 Recursion should make this a simple task. 递归应该使这成为一个简单的任务。

(define (append-first-to-end lst)
  (define (append-to-end a lst)
    (if (null? (cdr lst)) ???
      (cons ??? (append-to-end a ???))))
  (append-to-end (car lst) lst))

Between my example, Chris's example and my opening paragraph, you should be able to fill in the blanks. 在我的示例(克里斯的示例)和我的开篇段落之间,您应该可以填写空白。

I do hope the action required once you have the final s-expression from lst is obvious... 我确实希望一旦有了lst的最终s表达式后就需要采取的行动是显而易见的...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM