How to remove the first element from a list?
How do I remove the first element from a list, in Scheme?
Su开发者_如何学Goppose I have the following list
'((apple bob car) (cat dig) (e)))
How would I just get rid of apple
and leave the rest alone?
The three fundamental list operations in Scheme are
cdr
, which means 'rest' or 'give me the list, without the first item'car
, which means 'first' or 'give me the first item in the list'cons
, which means append lists
assuming that s is the list ((apple bob car) (cat dig) (e))
The intermediate steps
(car s) ; (apple bob car)
(cdr (car s)) ; (bob car)
(cdr s) ; ((cat dig) (e))
The final expression
(cons (cdr (car s))) (cdr s))
The result
((bob car) (cat dig) (e))
First, recognise that your question is a bit inconsistent. If you want to remove the first element in the list, you'll be left with
((cat dig) (e))
because the first element in the list is (apple bob car)
.
If you're trying to get rid of just apple
, then if the head (car) of the list is itself a list, you want to replace it with its cdr. I assume that you want this to work regardless of the depth of the list, so you'll need the method to be recursive (unlike the other answers).
So if the first item is a list, then you need to remove the first item from the list, and add it to the rest of the list, recursively. This seems to work:
(define removeFirst
(lambda (input)
(cond
((list? (car input)) (cons (removeFirst (car input)) (cdr input)))
(else (cdr input))
)
)
)
> (removeFirst '((apple bob car) (cat dig) (e)))
((bob car) (cat dig) (e))
In addition to the other answers, there's a flavor of mutation to your question, and lists in Scheme are generally immutable -- even lists within lists. That's why all the other answers returned a new list sans the element you wanted to be rid of. You can assign a list to a variable, and then assign a different list to the same variable using set! but you'll never change the list you first made.
(cdr x)
(where 'x' is a list) will give you all of the list except the first element. The problem with applying it to what you have above is that apple
isn't the first element of :'((apple bob car) (cat dig) (e)))
. What you've given is a list of lists, and the first element of the outer list is the list (apple bob car)
.
To remove only "apple", you need to figure out whether the first item in the list you received was itself a list, and if so put together a list consisting of that list with the first item removed (hint:recursion), followed by the remainder of your original list. If that first item isn't a list, then you just return the remainder of the list.
精彩评论