简体   繁体   中英

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 . 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. It works as expected:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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