简体   繁体   中英

In Racket how do i sum the alternating values in a list using recursion

I am writing a function using recursion that is supposed to add the alternating values in a list. It's relatively simple to just write some code to add all the values in the list but I am struggling to only add the alternating values in the list. If possible I would strongly prefer the code written using recursion over higher-order functions for this problem.

My only guess for this problem is to manipulate the length of the list to only add the alternating values of the list or to possibly find a way to only add the odd elements in the list but I have no clue if this is even possible and if it was even possible i would have no clue where to even begin.

This is my code so far

(define (skip-sum L)
  (cond
    [(empty? L) 0]
    [else (+ (first L) (skip-sum (rest L)))]))

This is what the results should look like. As you can see only the odd elements in the lists were summed showing only alternating values in the list were added.

(check-expect (skip-sum (list 4 6 8)) 12)
(check-expect (skip-sum (list 1 3 5 7 9 11)) 15)
(check-expect (skip-sum (list 2 10 4 12 6 14 8 12 10))30)

For instance for the second example the alternating values which were added are 1+5+9=15.

Here is a possibile recursive definition:

(define (skip-sum l)
  (cond ((empty? l) 0)
        ((empty? (cdr l)) (car l))
        (else (+ (car l) (skip-sum (cddr l))))))

Note that there are two cases to end the recursion: when the list is empty, or has only one element.

In the recursive case we simply sum the first element of the list with the result of calling the function on the list starting from the third one (and so ignoring the second one). In this way we skip every even element and obtain the correct sum.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM