;; Design power (exponent) function that computes x to the nth power ;; where n is a natural number ;; A Natural is one of: ;; - 0 ;; - (add1 Natural) ;----------------------- ;; Using Structural Recursion... ;; pow.v0 : Number Natural -> Number ;; x to the nth power (where n is a natural number) (define (pow.v0 x n) (cond [(zero? n) 1] [else (* x (pow.v0 x (sub1 n)))])) ;----------------------- ;; Using Generative Recursion... ;; pow : Number Natural -> Number ;; x to the nth power (where n is a natural number) ;; HOW: if n is even: compute x^(n/2) using recursion, ;; then square that [idea: x^n = (x^(n/2))^2] ;; if n is odd, compute (x^(n-1)) using recursion, ;; then multiply that by x [idea: x^n = (x * (x^(n-1)))] (define (pow x n) (cond [(zero? n) 1] [(= n 1) x] ;; -- complex case [(even? n) (local ((define y (pow x (/ n 2)))) (* y y))] [(odd? n) (* x (pow x (sub1 n)))])) (define (pow.v0 x n) (cond [(zero? n) 1] [else (* x (pow.v0 x (sub1 n)))])) (check-expect (pow 4 0) 1) (check-expect (pow 2 2) 4) (check-expect (pow 4 2) 16) (check-expect (pow 2 5) 32) (check-expect (pow 10 4) 10000)