How would you update a list by removing the first item?
consider the following pseudocode
define remover
(list = cdr list))
or is there a more recommendable way of removing the first item in a list?
How would you update a list by removing the first item?
consider the following pseudocode
define remover
(list = cdr list))
or is there a more recommendable way of removing the first item in a list?
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, be aware that the original list passed as a parameter to remover
will not be modified, instead a new list will be returned without the first element of the old list; that's the way to operate on immutable linked lists, you should never assume that any modifications on a list will occur in-place.
Beware!
There are no list data structure per se. So you can not take a list, l
, and remove the first element of l
.
What you can do, when given a list l
, is to use cdr
to produce a new list which has the same elements as l
does, except that the new list doesn't hold the first element.
A little more detail: A list holding the three values 1, 2, and, 3 is represented as (cons 1 (cons 2 (cons 3 '()))
.
Let us name the cons-cells:
c3 = (cons 3 '())
c2 = (cons 2 c3)
l = c1 = (cons 1 c2)
The first thing to note is that the entire list is given by the value c1. We can not delete the number 1 from the list by manipulating the cons-cell c1. We can however easily find a list omitting the first element, since
c2 = (cons 2 c3) = (cons 2 (cons 3 '())
Therefore (cdr l) = (cdr c1) = c2
will produce a new list omitting the first element.
Think about what cdr
does. Remember, cdr
returns a list. Your answer is close, you just need to think about it in terms of Scheme syntax and functions.