Binary 方案中二元表的乘法
我正在尝试实现一个算法,将1和0的两个位列表相乘,作为对二进制乘法的模拟。它应该会返回一个类似的列表,但我很难在我已经拥有的基础上进行构建。如果能得到一些帮助,我们将不胜感激Binary 方案中二元表的乘法,binary,scheme,lisp,Binary,Scheme,Lisp,我正在尝试实现一个算法,将1和0的两个位列表相乘,作为对二进制乘法的模拟。它应该会返回一个类似的列表,但我很难在我已经拥有的基础上进行构建。如果能得到一些帮助,我们将不胜感激 ;;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
;;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))))))))
基于,这里有一个适用于二进制数(按正确顺序)的解决方案:
所以
(apa-multi '(1 0 1 1 0) '(1 0 1))
=> '(1 1 0 1 1 1 0)
基于,这里有一个适用于二进制数(按正确顺序)的解决方案:
所以
(apa-multi '(1 0 1 1 0) '(1 0 1))
=> '(1 1 0 1 1 1 0)
如果
multiply
应该返回一个列表,那么子句[(zero?y)0]
是错误的;它不会返回列表。如果multiply
返回一个列表,那么z
是一个列表,那么(*10z)
和(+x(*10z))
将是错误的。一般来说,没有理由像如果布尔条件为true,则为false
,您只需执行布尔条件
。类似地,zero?
过程的主体可以是(或(null?x)(和(而不是(=(第一个x)1))(zero?(其余x)))
。不清楚num_偶?
应该做什么(注释会有帮助!),但同样的事情也适用于它;它可以简化为(或(null?x)(=(first x)0)(num_偶?(rest x))
。这里的具体问题是什么?您已经展示了一些代码,但没有展示它产生了什么,也没有展示它应该产生什么。“有关您编写的代码问题的问题必须描述具体问题……要求代码的问题必须表明对正在解决的问题的最低理解。包括尝试的解决方案、为什么不起作用以及预期结果。”二进制数据的数据结构是什么样的如果multiply
应该返回一个列表,那么子句[(zero?y)0]
是错误的;它不会返回列表。如果multiply
返回一个列表,那么z
是一个列表,那么(*10z)
和(+x(*10z))
将是错误的。一般来说,没有理由像如果布尔条件为true,则为false
,您只需执行布尔条件
。类似地,zero?
过程的主体可以是(或(null?x)(和(而不是(=(第一个x)1))(zero?(其余x)))
。不清楚num_偶?
应该做什么(注释会有帮助!),但同样的事情也适用于它;它可以简化为(或(null?x)(=(first x)0)(num_偶?(rest x))
。这里的具体问题是什么?您已经展示了一些代码,但没有展示它产生了什么,也没有展示它应该产生什么。“有关您编写的代码问题的问题必须描述具体的问题……询问代码的问题必须表明对正在解决的问题的最低理解。包括尝试的解决方案、为什么不起作用以及预期的结果。”二进制数据的数据结构是什么样的