Search code examples
listschememultiplication

How can I add a () in a list?


How can I add a parentheses in a list? For example,

(multiply '(1 2) '(1 2 3))

It should output ((1 2 3) (2 4 6))

This is what I have now

(define multiply
  (lambda (los1 los2)
    (cond
     ((null? los1) '())
     ((null? los2) '())
     (else (cons (* (car los1) (car los2))
         (append (multiply(list (car los1)) (cdr los2))
             (multiply(cdr los1) los2)))))))

The output I get is (1 2 3 2 4 6).

P/S: If this is a bad question or anything, don't hesitate to tell me or scold me. I am trying to learn to use stackoverflow.


Solution

  • Think about what the implications of the input and the output are. I imagine that you cannot do this with one single recursive procedure, but you can do it with two.

    (list-multiply 5 '(1 2 3)) 
    ; ==> (5 10 15)
    

    When you have that you iterate over the first list and use list-multiply for each element and of course the second argument is never iterated, it's just passed along.

    (multiply '(1 2) '(1 2 3))
    ; ==> (cons (list-multiply 1 '(1 2 3))
    ;           (cons (list-multiply 2 '(1 2 3))
    ;                  '()))
    ; ==> ((1 2 3) (2 4 6))
    

    You can implement this simply by useinfg higher order functions:

    (define (multiply lst1 lst2)
      (map (lambda (e1)
             (map (lambda (e2) (* e1 e2)) lst2))
           lst1))
    

    Notice the double map. One that iterates lst1 to make elements in the result and a second map that multiplies the one element with each element of the list. You might imagine that since these look similar the two recursive functions probably have a lot in common too.

    PS: Learn to solve your problems without list and append. (list 1 2 3) is just a procedure that is equivalent to (cons 1 (cons 2 (cons 3 '()))) and (append '(1 2 3) '(4 5 6)) is equivalent to (cons 1 (cons 2 (cons 3 '(4 5 6)))). Try always building lists from end to beginning and in the event you need the opposite it might just need a reverse in the end.