Removing an item from a list in a schematic

How would you update the list by removing the first item?

consider the following pseudocode

define remover
(list = cdr list))

      

or is there a more recommended way to remove the first item in the list?

+1


source to share


3 answers


You nailed it, just write it as a procedure:

(define (remover lst)
  (cdr l))

      

And use it like this (this creates a new binding and is not an assignment):

(let ((new-list (remover old-list)))
  new-list)

      



Or like this (this defines a new list):

(define new-list (remover old-list))

      

In any case, keep in mind that the original list passed as a parameter remover

will not be modified, instead the new list will be returned without the first element of the old list; That's the way to work with immutable linked lists, you should never assume that any changes to the list will happen in place.

+1


source


Caution!

The list data structure does not exist. Therefore, you cannot take the list l

and remove the first item l

.

What you can do if you specify a list l

is to use it cdr

to create a new list that has the same elements as l

, except that the new list does not hold the first element.

Few details. A list containing three values ​​1, 2 and, 3 is represented as (cons 1 (cons 2 (cons 3 '()))

. Name cons-cells:



       c3 = (cons 3 '()) 
       c2 = (cons 2 c3)
   l = c1 = (cons 1 c2)

      

First of all, it should be noted that the entire list is specified by the value c1. We cannot remove number 1 from the list by manipulating cons-cell c1. However, we can easily find a list excluding the first element, since

   c2 = (cons 2 c3) = (cons 2 (cons 3 '())

      

Therefore, it (cdr l) = (cdr c1) = c2

will create a new list excluding the first element.

+1


source


Think about what it does cdr

. Remember cdr

returns a list. Your answer is close, you just need to think about it in terms of schema syntax and functions.

0


source







All Articles