求和和(2x-1,x = 1 ... n)。我必须写一个递归函数来解决总和。
(define (sum1 n)
(if (= n 0)
-1
(+ n (- 1 (sum1 (* n 1))))))
这就是我到目前为止,我迷失了。
你的基本情况是1
而不是0
,因为你只是从1
到n
定义它。因此,该函数仅在N
上定义。所以我们不需要考虑函数的0
情况(它只消耗N
s)。
此外,递归调用应该将应用于2x-1
的n添加到序列的其余部分的总和。目前该函数没有终止,因为您在相同的输入(* n 1) = n
上调用它。 (sum1 n) => (sum1 n) => ...
#lang racket
(require rackunit)
;; N is one of:
;; - 1
;; - (+ 1 N)
;; interpretation: 1, 2, 3 ...
;; N -> Number
;; sums `(- (* 2 x) 1)` from 1 to n
(define (sum1 n)
(if (= n 1)
(- (* 2 1) 1) ;; = 1
(+ (- (* 2 n) 1) (sum1 (- n 1)))))
(check-equal? (sum1 1) 1)
(check-equal? (sum1 10) 100)
摘要功能:
;; [Number -> Number] N -> Number
;; sums of f from 1 to n
(define (summation f n)
(if (= n 1)
(f 1)
(+ (f n) (summation f (- n 1)))))
(check-equal? (summation identity 5) (+ 1 2 3 4 5))
(check-equal? (summation sqr 3) (+ (sqr 1) (sqr 2) (sqr 3)))
(check-equal? (summation (λ (x) (- (* 2 x) 1)) 1) 1)
(check-equal? (summation (λ (x) (- (* 2 x) 1)) 10) 100)
如果你只想输出总和,我就是这样做的:
#lang racket
(define (sum n)
(if (= n 1)
1
(+ (-(* 2 n) 1) (sum (- n 1)))))