A scheme procedure that returns a list of every other element

前端 未结 2 1558
慢半拍i
慢半拍i 2021-01-21 04:43

I\'m having a bit of trouble implementing this program in Scheme, although I think I\'m 90% of the way there. Unfortunately I need to be a little vague about it since this is a

2条回答
  •  Happy的楠姐
    2021-01-21 04:55

    This one is considerably simpler than the previous question you asked. Bear in mind, you don't have to calculate the length at each step (that could be very inefficient), or use append operations to solve it (use a cons instead); here's the structure of the answer, because it looks like homework I'l let you fill-in the blanks:

    (define (every-other lst)
      (if (or                     ; if the list is empty 
              )                   ; or the list has a single element
                                  ; then return the empty list
          (cons                   ; otherwise `cons` the second element
                (every-other )))) ; and recursively advance two elements
    

    If you need to do some error checking first, use another function and call the above procedure after you're certain that the arguments are correct:

    (define (other_el lst)
      (if (list? lst)
          (every-other lst)
          (error "USAGE: (other_el [LIST])")))
    

    Use it like this:

    (other_el '(A B C D E G))
    => '(B D G)
    

提交回复
热议问题