Dovakin940
Dovakin940

Reputation: 63

Scheme : Make operations on a list without changing its copy?

I have a helper to copy a list :

(define (list-copy list)
  (if (null? list)
      '()
      (cons (car list) (list-copy (cdr list)))))

Then,

(define (multList lst1 lst2)
  (define lstCopy2 (list-copy lst2))  
  (cond ((null? lst1) ())
        ((eq? (length lst1) (length lst2)) (cons (* (car lst1) (car lst2)) (multList (cdr lst1) (cdr lst2)))) 
        ((> (length lst1) (length lst2))
         (if (null? lst2) lstCopy2
         (cons (* (car lst1) (car lst2)) (multList (cdr lst1) (cdr lst2)))))
        (else '())))

I'm trying to copy lst2 into lstCopy2 and then I would like lstCopy2 to stay intact when I'm working on lst2 in order to call lst2 (with the help of lstCopy2) as it was at first. In my 3rd cond (when lenght lst1 > lenght lst2) when lst2 = () I would like to continue the process until lst1 is ().

Thanks for your help

Upvotes: 1

Views: 190

Answers (2)

Sylwester
Sylwester

Reputation: 48745

As far as I can see your copy is not used. In addition, none of the procedure mutates anything so (equal? lst2 lstCopy2) will always be #t for every recursion / element of the list.

If lst1 is shorter than lst2 or you've reached the end of the list you will get an error since () is an illegal expression. perhaps you meant '()?

This could have been written a lot easier:

(require srfi/1)

(define (multList lst1 lst2)
  (define (aux lst1 lst2)
    (if (null? lst2)
        '()
        (cons (* (car lst1) 
                 (car lst2)) 
              (aux (cdr lst1) (cdr lst2)))))
  (aux (apply circular-list lst1) lst2))

(multList '(1 -1) '(1 2 3 4 5 6)) ; ==> (1 -2 3 -4 5 -6)

;; with srfi-1-version of map we can use it to make the code shorter
(define (multList lst1 lst2)
  (map * (apply circular-list lst1) lst2))

Upvotes: 2

WorBlux
WorBlux

Reputation: 1413

You're going about this in a very odd way. The standard way to do this is the define an inner function. Usually you inner function and then call it.

The way you were doing it you were making a copy of lst2 every time you called multList, which is not what i think you want.

But I don't see where you actually reference the original 2nd list so I don't see the reason behing what you want to do.

(define (multList oL1 oL2)
  (define (helper lst1 lst2)
     (cond ((null? lst1) '())   
           ((null? lst2) (helper lst1 oL2))
           (else
            (cons (* (car lst1) (car lst2)) 
                  (helper (cdr lst1) (cdr lst2))))))
  (helper oL1 oL2))

(multlist '(9 2 4) '(1 2))

;Value 14: (9 4 4)

(multlist '(1 2) '(9 2 4))

;Value 15: (9 4)

See what I mean about not really being a proper multiplication? (multist a b) is not always the same as (multlist b a).

Upvotes: 1

Related Questions