removing last element of a list(scheme)

后端 未结 6 1888
轻奢々
轻奢々 2021-02-07 17:44

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:35

    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.

提交回复
热议问题