1
Я пытаюсь реализовать алгоритм для умножения двух битовых списков 1s и 0s в качестве имитации для двоичного умножения. Он должен возвращать подобный список, но мне сложно строить то, что у меня уже есть. Некоторую помощь была бы оценена ...Умножение двоичного списка в схеме
;;Function designed to accept two bit-list binary numbers (reverse order) and produce their product, a bitlist in reverse order.
;;Example: (multiply '(0 1 1 0 1) '(1 0 1)) should produce '(0 1 1 1 0 1 1)
(define (multiply x y)
(cond
;[(= null? y) 0]
[(zero? y) 0]
(#t (let ((z (multiply x (rest y)))) (cond
[(num_even? y) (cons 0 z)]
(#t (addWithCarry x (cons 0 z) 1)))))))
;This is to check if the current value of parameter x is the number 0
(define (zero? x)
(cond
((null? x) #t)
((=(first x) 1) #f)
(#t (zero? (rest x)))))
;This is to check if the current parameter x is 0 (even) or not.
(define (num_even? x)
(cond
[(null? x) #t]
[(=(first x) 0)#t]
[#t (num_even? (rest x))]))
;To add two binary numbers
(define(addWithCarry x y carry)
(cond
((and (null? x) (null? y)) (if (= carry 0) '() '(1)))
((null? x) (addWithCarry '(0) y carry))
((null? y) (addWithCarry x '(0) carry))
(#t (let ((bit1 (first x))
(bit2 (first y)))
(cond
((=(+ bit1 bit2 carry) 0) (cons 0 (addWithCarry (rest x)(rest y) 0)))
((=(+ bit1 bit2 carry) 1) (cons 1 (addWithCarry (rest x)(rest y) 0)))
((=(+ bit1 bit2 carry) 2) (cons 0 (addWithCarry (rest x)(rest y) 1)))
(#t (cons 1 (addWithCarry (rest x) (rest y) 1))))))))
Если 'multiply' должен возвращать список, тогда предложение' [(zero? y) 0] 'неверно; он не возвращает список. И если 'multiply' возвращает список, тогда' z' - это список, тогда '(* 10 z)' и '(+ x (* 10 z))' будут ошибки. –
Как общее стилистическое примечание, нет оснований делать что-то вроде 'if boolean-condition then true else false', вы просто выполняете' boolean-condition'. Точно так же тело вашей процедуры «zero?» Может быть просто «(или (null? X) (и (not (= (first x) 1)) (zero? (Rest x)))). –
Непонятно, что должно делать 'num_even?' (Комментарии помогут!), Но то же самое относится и к нему; его можно упростить как '(или (null? x) (= (first x) 0) (num_even? (rest x))). –