Search code examples
schemelispracket

How to fix error with Sum of close pairs on the list


I want to sum each list of 2 pairs close and return a new list where each organ is the sum of the next 2 pairs.

i have this code:

what i do wrong?

(define (add-consecutives lst)
(if (null? (Cdr lst)
                 Null
                (cons
                      (+ (car lst) (cadr lst)
                       (add-consecutives (cadr lst )))))))

(add-consecutives (list 1 2 3 4))

when i run it i get bad syntax. what i do wrong?

thank's...


Solution

  • There are a couple of syntax problems. For starters, you forgot to close the parentheses for the null? call, and also the parentheses in the recursive step are misplaced. All this can be avoided by properly indenting the code and using an IDE with syntax highlighting.

    There are deeper problems, too. The way you're advancing the recursion is incorrect (you need to move to the rest of the list) and you should handle the edge cases when there are 0, 1, 2 elements left. This should address all the issues:

    (define (add-consecutives lst)
      (cond ((null? lst) null)
            ((null? (cdr lst))  (list (car lst)))
            ((null? (cddr lst)) (list (+ (car lst) (cadr lst))))
            (else (cons (+ (car lst) (cadr lst))
                        (add-consecutives (cdr lst))))))
    

    Let's try some tests:

    (add-consecutives (list))
    => '()
    (add-consecutives (list 1))
    => '(1)
    (add-consecutives (list 1 2))
    => '(3)
    (add-consecutives (list 1 2 3))
    => '(3 5)
    (add-consecutives (list 1 2 3 4))
    => '(3 5 7)