removing last element of a list(scheme)

后端 未结 6 861
忘了有多久
忘了有多久 2021-02-07 18:17

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)
         


        
6条回答
  •  后悔当初
    2021-02-07 18:34

    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.

提交回复
热议问题