So I have to remove the last element of a list in scheme.
For example, let's say I have a list (1 2 3 4)
. I need to return:
(1 2 3)
My idea:
reverse(list)
car(list)
reverse(list)
Is there a reverse
function in scheme(racket)?
So I have to remove the last element of a list in scheme.
For example, let's say I have a list (1 2 3 4)
. I need to return:
(1 2 3)
My idea:
reverse(list)
car(list)
reverse(list)
Is there a reverse
function in scheme(racket)?
I would write a simple recursion, altering the typical "empty? mylist" base case to "empty? (rest mylist)," so that I can return empty when the input list is only 1 element.
By the way, this code is in Racket/PLT Scheme, a subset of Scheme.
You wrote: "reverse, car, reverse". I believe you meant to write "reverse, cdr, reverse". There's nothing wrong with this solution; it's linear in the size of the list, just like any solution to this that uses the standard lists.
As code:
If the multiple traversal of the list or the needless construction of another list copy bothers you, you can certainly avoid it, by writing the thing directly.
Given your almost-solution, I'm going to assume that this isn't homework.
Here's what it would look like, in racket:
I would do a recursive function that goes down the list and attaches the element (using
cons
) if the element after it is not the last, and appends nothing if it isn't.I haven't done scheme for years though so that's as far as I can go.
Someone can run with how to implement it (unless it's homework then they probably shouldn't!)
There is a
reverse
, but using it would not be very efficient. I suggest the following recursive function.The
if
checks whether it is at the last element of the list.I've done something simpler than: reverse(list), car(list), reverse(list) to get the last element, check out:
SRFI 1 (activate in Racket using
(require srfi/1)
) has adrop-right
function: