Schematic: Add to List of Records

I am working on the purpose of the scheme for the school, and the question arises related to the fact that we define the record "type" (implemented as a list) (which is a musical record).

The question that I have problems with, I asked to create a procedure that creates a list of these records, and then a function to add an entry to this list. It is pretty simple, but I feel that something may be wrong.

I know how to add an item to the list (i.e. the record shelf in this example), but I'm not sure how to properly maintain this list through calls to this add function. Here is what I have:

 (define (add-record record lst) (append lst (list record))) 

Which works as I expected, but my problem is when I call this procedure.

 (define record-self '()) 

Was there my first attempt, but, of course, every time I add an entry using the add-record procedure, going to this only certain record-shelf list, my add function returns a new list (that is, a copy with the attached record). It makes sense, but I'm not sure if this is what I want.

So, if I wanted to add a few entries to the list:

 (add-record highway61 record-shelf) (add-record sgtPepper record-shelf) 

Of course, this does not lead to what I want, because record-shelf not updated. And I do not think that at this moment we should use set! or destination.

Should I just collect a copy of the returned list (from add-record ) each time, and then use this returned list in the next call?

+4
source share
1 answer

You want state-related behavior. As Enrique says, the answer to your last question is yes.

Is there a reason you can't just cons write a new entry to the head of the list? This is an idiomatic way to add items to a list in Lisp. Or in any functional language that uses separate lists.

 (define (add-record record lst) (cons record lst)) (define newshelf (add-record 36chambers oldshelf)) 

There is no way to make record-shelf contain a new item after calling add-record without using set! in some form.

+3
source

All Articles