添加列表中所有值可被5整除的元素

时间:2018-07-16 03:02:51

标签: functional-programming scheme racket

我正在尝试使用尾递归,但是我被卡住了。请帮助

(define (sum-divis-five lst)
    (helper-function lst 0))

(define (helper-function lst answer)
    (cond[(empty? lst) answer]
         [else (if (= 0 (remainder (car lst) 5))
                   ????)
                   (helper-function (cdr lst) answer)]))

2 个答案:

答案 0 :(得分:1)

填写

(define (sum-divis-five lst)
    (helper-function lst 0))

(define (helper-function lst answer)
    (cond ((empty? lst) answer)
          ((= 0 (remainder (car lst) 5)) (helper-function (cdr lst) (+ (car lst) answer)))
          (else (helper-function (cdr lst) answer))))

使用letrec

一个人也可以使用函数内的letrec

(define (sum-divis-five L)
  (letrec ((i-sum-divis-five (lambda (L acc)
                               (cond ((empty? L) acc)
                                     ((= 0 (remainder (car L) 5))
                                      (i-sum-divis-five (cdr L)
                                                        (+ (car L) acc)))
                                     (else (i-sum-divis-five (cdr L) acc))))))
    (i-sum-divis-five L 0)))

更一般

或广义的:

(define (sum-divisibles L n)
  (letrec ((i-sum-divs (lambda (L n acc)
                         (cond ((empty? L) acc)
                               ((= 0 (remainder (car L) n))
                                (i-sum-divs (cdr L) n (+ (car L) acc)))
                               (else (i-sum-divs (cdr L) n acc))))))
    (i-sum-divs L n 0)))

使用:

(sum-divisibles '(1 2 3 4 5 10 15 3) 5)
;; 30

特殊情况为5

(define (sum-divis-five L)
  (sum-divisibles L 5))

(sum-divis-five '(1 2 3 4 5 10 15 3))
;; 30

答案 1 :(得分:0)

如果您为变量命名,将会更好地了解正在处理的内容。 也尝试将问题分为较小的问题。

方法 您要过滤掉所有不能被5整除的数字,然后将过滤后的列表中的所有数字相加。

示例

输入:1 2 3 4 5 6 7 10 12 15 3 5

过滤器:5 10 15 5

总和:35

代码(辅助)

(define (is-divisible-by? dividend divisor)
  (zero? (remainder dividend divisor)))

(define (is-divisible-by-5? dividend)
  (is-divisible-by? 5))

代码(非尾递归)

(define (filter predicate list)
  (if (empty? list)
      '()
      (let ([element (car list)]
            [rest (cdr list)])
        (if (predicate element)
            (cons element (filter predicate rest))
            (filter predicate rest)))))

(define (sum list)
  (if (empty? list)
      0
      (let ([element (car list)]
            [rest (cdr list)])
        (+ element (sum rest)))))

代码(尾递归)

(define (filter predicate list result)
  (if (empty? list)
      result
      (let ([element (car list)]
            [rest (cdr list)])
        (if (predicate element)
            (filter predicate rest (cons element result))
            (filter predicate rest result)))))

(define (sum list result)
  (if (empty? list)
      result
      (let ([element (car list)]
            [rest (cdr list)])
        (sum rest (+ element result)))))

通话

(define (solution list)
  (sum (filter is-divisible-by-5? list '()) 0))