简体   繁体   English

基于加法函数的两个一元列表的乘法

[英]Multiplication of two unary lists based on the addition function

(define unary-add
  (lambda (list1 list2)
    (if (pair? list1)
        (cons (car list1)
              (unary-add (cdr list1) list2))
        list2)))

I performed the addition of two unary representations of lists as above. 我执行了清单的两个一元表示的加法运算。 Now I want to multiply them, considering multiplication as the repeated addition. 现在,我想将它们相乘,将乘法视为重复的加法。 So, I made use of this function, and did the below: 因此,我利用了此功能,并进行了以下操作:

(define unary-mul
  (lambda (list1 list2)
    (if (pair? list1)
        (cons (car list1)
              (unary-mul (unary-add (cdr list1) list2)))
        list2)))

On running the code, it says arguments do not match. 在运行代码时,它说参数不匹配。 Where did I went wrong? 我哪里出问题了?

Your current approach doesn't seem right - the recursive call is misplaced, and the error reported indicates that you forgot to pass the second parameter to unary-mul . 您当前的方法似乎不正确-递归调用被放错了位置,并且报告的错误表明您忘记了将第二个参数传递给unary-mul Try this instead: 尝试以下方法:

(define unary-mul
  (lambda (list1 list2)
    (if (pair? list2)
        (unary-add list1
                   (unary-mul list1 (cdr list2)))
        '())))

Explanation: a multiplication is just a repeated addition, in the above code we keep adding list1 and decreasing the length of list2 until it's empty. 说明:乘法只是重复的加法,在上面的代码中,我们继续添加list1并减小list2的长度,直到它为空。 It works as expected: 它按预期工作:

(unary-mul '(x x x) '(x x))
=> '(x x x x x x)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM