A scheme procedure that returns a list of every other element

前端 未结 2 1545
慢半拍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条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-21 05:00

    There are a number of minor issues with this code that should be mentioned before I demonstrate the proper code.

    1. Do not capitalize procedures' names such as cdr and define in Scheme.
    2. Do not display an error message manually. Use exceptions.
    3. You should always indent your code. (edit: it looks like someone has edited the question's code to include indentation)

    Anyway, here is the function you are looking for:

    (define (evens lst)
      (if (or (null? lst)             ; if the list is empty 
              (null? (cdr lst)))      ; or the list has a single element
          '()                         ; then return the empty list
          (cons (cadr lst)            ; otherwise `cons` the second element
                (evens (cddr lst))))) ; and recursively advance two elements
    

    I tested the function in DrRacket 5.3 and (evens '(A B C D)) returns '(B D), as you specified. If you have any trouble, let me know. Good luck with your homework!

提交回复
热议问题