sicp-exs/sicp-ex-1.18.rkt

29 lines
541 B
Racket
Raw Normal View History

2020-08-21 19:22:56 +02:00
(define (divide a b)
(define (iter a b product)
(cond ((= a 0) product)
((< a 0) (- product 1))
(else (iter (- a b) b (+ product 1)))))
(iter a b 0))
; divide
(define (halve a)
(divide a 2))
(define (double a)
(+ a a))
(define (multiply a b)
(define (iter a b product)
(cond ((= a 1) (+ product b))
((even? a) (iter (halve a) (double b) product))
(else (iter (halve a) (double b) (+ product b)))))
(iter a b 0))
; multiply
(multiply 132 555)
(multiply 32 2)
(multiply 33 1)