0
votes

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}.

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. Since scheme is dynamically typed, I can't store the first element anywhere (at least I don't think I can).

How can I get this to work, using only the basic list functions? (e.g., cons, cons?, empty? first, last, rest)

2

2 Answers

1
votes

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. 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. 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...

2
votes

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).