user258875
user258875

Reputation:

Scheme looping through list

I am trying to write some code that will loop through a list and add like terms. I'm trying to cons the cdr of the input list to a null list and then just compare the car of the list to the car of the new list and traverse down the list but my code just isn't working. What am I doing wrong here?

  (define loop-add
  (lambda (l temp outputList)
    (if (or (equal? (cdr l) '()) (equal? (pair? (car l)) #f))
        outputList
        (if (equal? l '())
            outputList
            (let ((temp (cdr l)))
              (if (equal? temp '())
                  (loop-add (cdr l) outputList)
                  (if (equal? (cdr (car l)) (cdr (car temp)))
                      (loop-add l (cdr temp) (cons (append (cdr (car l)) (cdr (car (cdr l)))) outputList))
                      (loop-add l temp outputList))))))))

but the problem now is at the end line its just going to be an infinite loop. I need a way to recur with the input list but with temp being the cdr of the previous temp list.

Upvotes: 0

Views: 4205

Answers (2)

Sam Tobin-Hochstadt
Sam Tobin-Hochstadt

Reputation: 5053

Here's a simple solution in Racket:

(define (loop-add l)
  (define table
    (for/fold ([h (hash)]) ([i l])
       (dict-update h (cadr i) (lambda (v) (+ v (car i))) 0)))
  (dict-map table (lambda (key val) (list val key))))

(loop-add '((2 1) (3 4) (5 3) (2 4)))

Upvotes: 1

Nietzche-jou
Nietzche-jou

Reputation: 14730

Start by writing a procedure that can transform your input list into a new list of the unique terms in the original list, so

(get-unique-terms '((2 1) (3 4) (5 3) (2 4)))
(1 4 3) ; or something like that

Call this new list TERMS. Now for each element in TERMS you can search the original list for matching elements, and get a sum of the coefficients:

(define (collect-like-terms l)
  (let ((terms (get-unique-terms l)))
    ;; For each element of TERMS,
    ;;   Find all elements of L which have a matching term,
    ;;      Sum the coefficients of those elements,
    ;;      Make a record of the sum and the term a la L.
    ;; Collect the results into a list and return.

Upvotes: 1

Related Questions