Scheme循环遍历列表

时间:2010-10-24 21:49:13

标签: scheme

我正在尝试编写一些代码,这些代码将遍历列表并添加类似的术语。我正在尝试cons输入列表的cdr到空列表,然后只需将列表的car与新列表的car进行比较并遍历在列表中,但我的代码不起作用。我在这里做错了什么?

  (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))))))))

但现在的问题是在终点线它只是一个无限循环。我需要一种方法来重复输入列表,但temp是前一个临时列表的cdr。

2 个答案:

答案 0 :(得分:1)

首先编写一个程序,将您的输入列表转换为原始列表中唯一术语的新列表,所以

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

将此新列表称为TERMS。现在,对于TERMS中的每个元素,您可以在原始列表中搜索匹配的元素,并获得系数的总和:

(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.

答案 1 :(得分:1)

这是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)))