开发者

Racket-related question

开发者 https://www.devze.com 2023-04-01 03:35 出处:网络
(define (mult a b);;function mult(a,b) (cond ((IsItZero? b) 0);;if b = 0: return 0 ((let((c (mult a (rest b))));;c = mult(a, floor(b/2))
 (define (mult a b)                    ;;function mult(a,b)
 (cond                                 
 ((IsItZero? b) 0)                     ;;if b = 0: return 0   
 ((let((c (mult a (rest b))))          ;;c = mult(a, floor(b/2))
 (if (= (first b) 0)                   ;;if b is even
 (cons (0 c))                          ;;return 2c e开发者_如何学运维lse:
 (addTogether(a cons(0 c))))))))       ;;return a + 2c

At the right, in the comments, is some pseudocode given for a multiplication algorithm. On the left is my attempt at implementing said algorithm in, well, real code, taking two lists of binary digits as parameters (From left to right, as opposed to right to left). I get an error when running it that says something along the lines of "procedure application: expected procedure, given: 0; arguments were: 0." Other functions seen within work perfectly on their own.

Can anyone provide me a hint or nudge in the right direction?


It's (cons 0 c), not (cons (0 c)). :-) Even so, cons is the wrong approach here. :-)

Here's how I'd translate it:

(define (mult a b)
  (if (zero? b) 0
      (let ((c (mult a (quotient b 2))))
        (if (even? b)
            (* 2 c)
            (+ a (* 2 c))))))

A less-literal translation can make the code slightly more readable:

(define (mult a b)
  (if (zero? b) 0
      (let ((c (mult a (quotient b 2))))
        (if (even? b)
            (+ c c)
            (+ a c c)))))

ETA: Binary digit edition! (Where, say, 4 is represented as '(0 0 1).)

(define (mult a b)
  (if (null? b) '()
      (let ((c (mult a (cdr b))))
        (if (zero? (car b))
            (cons 0 c)
            (add a (cons 0 c))))))

(where you have to implement add to do binary-digit addition.)

0

精彩评论

暂无评论...
验证码 换一张
取 消