removing last element of a list(scheme)

元气小坏坏 提交于 2019-12-03 16:37:08

问题


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)?


回答1:


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:

;; all-but-last: return the list, not including the last element
;; list? -> list?
(define (all-but-last l) (reverse (cdr (reverse l))))

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:

#lang racket

(require rackunit)

;; all-but-last : return the list, except for the last element
;; non-empty-list? -> list?
(define (all-but-last l)
  (cond [(empty? l) (error 'all-but-last "empty list")]
        [(empty? (rest l)) empty]
        [else (cons (first l) (all-but-last (rest l)))]))

(check-equal? (all-but-last '(3 4 5))
              '(3 4))



回答2:


There is a reverse, but using it would not be very efficient. I suggest the following recursive function.

(define (remove-last lst)
    (if (null? (cdr lst))
        '()
        (cons (car lst) (remove-last (cdr lst)))))

(remove-last '(1 2 3 4)) ; returns '(1 2 3)

The if checks whether it is at the last element of the list.




回答3:


SRFI 1 (activate in Racket using (require srfi/1)) has a drop-right function:

 (drop-right '(1 2 3 4) 1)   ; => (1 2 3)



回答4:


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!)




回答5:


I've done something simpler than: reverse(list), car(list), reverse(list) to get the last element, check out:

(define (last-one liste)
  (if(null? (cdr liste))
     null
     (cons (car liste) (last-one (cdr liste)))
  )
)



回答6:


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.

(define (removelast mylist)
  (cond
    [(empty? (rest mylist)) empty]
    [(cons? mylist) (cons (first mylist) (removelast (rest mylist)))]))

(removelast (list 1 2 3 4 5))

By the way, this code is in Racket/PLT Scheme, a subset of Scheme.



来源:https://stackoverflow.com/questions/5006750/removing-last-element-of-a-listscheme

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!