I defined a new multiply function in Scheme which I think should be wrong, however, it works

StackOverflow https://stackoverflow.com/questions/19129520

  •  30-06-2022
  •  | 
  •  

Вопрос

In scheme, the new multiply function is:

( define ( iter b a n)
    ( cond (( = b 0) n)
           (( even? b) ( iter ( / b 2) ( * 2 a) n))
           ( else ( iter ( - b 1) ( / ( * a b) ( - b 1)) ( + a ( * a ( - b 1)))))))

( define ( mul b a)
    ( iter b a 1))

the question requires me to use iterative method rather than recursive method to deal with this problem, my thinking is following:

for example: ( mul 2 3 ) 

        b     a     n

 begin: 2     3     1
 1    : 1     6     1
 2    : 0     6/0   6

Obviously, in step 2, a equals 6/0. That should be impossible. But the function works well. Could anyone explain this? Here is the example in an online Scheme interpreter.

Это было полезно?

Решение

No, the function doesn't work well. Copy a fresh definition of the procedure, run it again and you'll see the error:

(define (iter b a n)
  (cond ((= b 0) n)
        ((even? b)
         (iter (/ b 2) (* 2 a) n))
        (else
         (iter (- b 1) (/ (* a b) (- b 1)) (+ a (* a (- b 1)))))))

(define (mul b a)
  (iter b a 1))

(mul 2 3)
=> /: division by zero

In fact, the expected solution would be more along these lines, and notice that special care must be taken in case that b is negative:

(define (iter a b n)
  (cond ((zero? b) n)
        ((even? b)
         (iter (+ a a) (/ b 2) n))
        (else
         (iter a (- b 1) (+ a n)))))

(define (mul a b)
  (if (< b 0)
      (- (iter a (- b) 0))
      (iter a b 0)))

And following your example, here's how the parameters look in each iteration when we execute (mul 2 3):

        a     b     n
 begin: 2     3     0
 1    : 2     2     2
 2    : 4     1     2
 3    : 4     0     6
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top