solutions/Structure and Interpretatio.../sicp-ex-1.32.rkt

35 lines
1016 B
Racket

#! /usr/bin/racket
#lang racket/base
(define (accumulate-iter combiner null-value term a next b)
(define (iter a result)
(if (> a b)
result
(iter (next a) (combiner (term a) result))))
(iter a null-value))
(define (product-iter term a next b)
(accumulate-iter * 1 term a next b))
(define (sum-iter term a next b)
(accumulate-iter + 0 term a next b))
(sum-iter (lambda (x) x) 1 (lambda (x) (+ x 1)) 4)
(product-iter (lambda (x) x) 1 (lambda (x) (+ x 1)) 4)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define (accumulate-recur combiner null-value term a next b)
(if (> a b)
null-value
(combiner (term a)
(accumulate-recur combiner null-value term (next a) next b))))
(define (product-recur term a next b)
(accumulate-recur * 1 term a next b))
(define (sum-recur term a next b)
(accumulate-recur + 0 term a next b))
(sum-recur (lambda (x) x) 1 (lambda (x) (+ x 1)) 4)
(product-recur (lambda (x) x) 1 (lambda (x) (+ x 1)) 4)