(Scheme) How do I add 2 lists together that are different sizes -
i'm new scheme , i'm having trouble trying add 2 lists of different sizes. wondering how add 2 lists of different sizes correctly. in code compared values , append '(0) shorter list can equal sizes, after doing can not use map add 2 lists. error code after running program. results should getting '(2 4 5 4). me out? thanks.
#lang racket (define (add lst1 lst2) (cond [(< (length lst1) (length lst2)) (cons (append lst1 '(0)))] [else lst1]) (cond ((and (null? lst1)(null? lst2)) null) (else (map + lst1 lst2)))) ;;result should '(2 4 6 4) (add '(1 2 3) '(1 2 3 4)) error:
cons: arity mismatch; expected number of arguments not match given number expected: 2 given: 1 arguments...: '(1 2 3 0)
the problem code there 2 cond expressions one after other - both execute, result of second 1 returned - in other words, code not doing think it's doing. now, solve problem it'll easier if split solution in 2 parts (in general, that's strategy!). try this:
(define (fill-zeroes lst n) (append lst (make-list (abs n) 0))) (define (add lst1 lst2) (let ((diff (- (length lst1) (length lst2)))) (cond [(< diff 0) (map + (fill-zeroes lst1 diff) lst2)] [(> diff 0) (map + lst1 (fill-zeroes lst2 diff))] [else (map + lst1 lst2)]))) explanation:
- the
fill-zeroesprocedure takes care of filling tail of list given number of zeroes - the
addprocedure in charge of determining list needs filled, , when both lists have right size performs actual addition
it works expected combination of list lengths:
(add '(1 2 3 4) '(1 2 3)) => '(2 4 6 4) (add '(1 2 3) '(1 2 3 4)) => '(2 4 6 4) (add '(1 2 3 0) '(1 2 3 4)) => '(2 4 6 4)
Comments
Post a Comment