简体   繁体   中英

Scheme - Recursion : Sum consecutive elements of a list

I'm trying to write a function using Scheme that :

  1. take a list of integers with more than two elements as a parameter
  2. sum the n-th-element and (n+1)-th-element
  3. return this list

Result should be as follows :

> (SumNeighbors (list 1 2 3 4))
(3 5 7)

I think I get the way to add elements but my recursion is totally wrong...

(define (SumNeighbors lst)
  (if (not (null? (cdr lst)))
      (append (list (+ (car lst) (car (cdr lst)))) (SumNeighbors (cdr lst)))))

Any help would be appreciated.

The solution to this problem follows a well-known pattern. I'll give you some hints, it'll be more fun if you find the answer by your own means:

(define (SumNeighbors lst)
  (if <???>                    ; if there's only one element left
      <???>                    ; we're done, return the empty list
      (cons                    ; otherwise call `cons`
       (+ <???> <???>)         ; add first and second elements
       (SumNeighbors <???>)))) ; and advance recursion

Notice the following:

  • Your solution is lacking the base case - what happens when the list we're traversing only has one element left? it's time to finish the recursion! and because we're building a list as the output, what should be the value returned?
  • We normally use cons to build an output list, not append . That's the natural way to build a list
  • The part of this procedure that falls outside the solution template is the fact that we stop when there's a single elment left in the list, not when the list is empty (as is the usual case)

You'll see that many procedures that iterate over an input list and return a list as output follow the same solution template, it's very important that you learn how and why this works, it's the foundation for writing solutions to other similar problems.

#!r6rs
(import (except (rnrs base) map)
        (only (srfi :1) map))

(define (sum-neighbors lst)
  (map + lst (cdr lst)))

The higher order function map as defined in SRFI-1 supports uneven lenght arguments. It will stop at the shortest list.

If you call (sum-neighbors '(1 2 3 4)) it will become (map + (1 2 3 4) (2 3 4)) which is the same as (cons (+ 1 2) (cons (+ 2 3) (cons (+ 3 4) '())))

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