Reputation: 1
Summation sum(2x-1, x=1...n). I have to write a recursive function to solve the sum.
(define (sum1 n)
(if (= n 0)
-1
(+ n (- 1 (sum1 (* n 1))))))
This is what I have so far, I am so lost.
Upvotes: 0
Views: 766
Reputation: 95
If you just want to output the sum, this is how I would do it:
#lang racket
(define (sum n)
(if (= n 1)
1
(+ (-(* 2 n) 1) (sum (- n 1)))))
Upvotes: 0
Reputation: 2137
Your base case is 1
not 0
because you're only defining it from 1
to n
. Therefore, the function is only defined over N
. So we don't need to consider the 0
case for the function (it only consumes N
s).
Furthermore, the recursive call should add n applied to 2x-1
to the summation of the rest of the sequence. Currently the function does not terminate because you are calling it on the same input (* 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)
Abstracting out the function:
;; [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)
Upvotes: 1