3
(define (associate lst)
    (if (or (null? lst) (= (length lst) 1))
        '()
        (cons (cons (car lst) (cadr lst)) (associate (cddr lst)))))

(define (disassociate lst)
    ;(display (caar lst))
    (if (null? lst)
        '()
        (cons (cons (caar lst) (cdar lst)) (disassociate (cdr lst)))))

(display (disassociate '((a . 1) (b . 2) (c . 3))))
(newline)
(display (associate '(a 1 b 2 c)))
(newline)

输出:

;; with list
((a 1) ((b 2) ((c 3) ())))
((a . 1) (b . 2))

;; with cons
((a . 1) (b . 2) (c . 3))
((a . 1) (b . 2))

我正在尝试将关联列表展平,Scheme但即使我将其更改listcons. 难道我做错了什么?

4

2 回答 2

3

您的disassociate行需要阅读:

(cons (caar lst) (cons (cdar lst) (disassociate (cdr lst)))))

准报价!有时这些使用准引用更清楚地实现,因为准引用可以让您看到生成的列表结构。

(define (associate lst)
  (if (or (null? lst) (null? (cdr lst)))
       '()
       `(,(cons (car lst) (cadr lst)) ,@(associate (cddr lst)))))

(define (disassociate lst)
  (if (null? lst)
      '()
      `(,(caar lst) ,(cdar lst) ,@(disassociate (cdr lst)))))

> (associate (disassociate '((a . 1) (b . 2))))
((a . 1) (b . 2))

请注意,您也可以将associate准报价写为:

       `((,(car lst) . ,(cadr lst)) ,@(associate (cddr list)))))

但这对我来说开始变得越来越难阅读,即使它使关联对变得明确。

于 2013-09-10T15:32:03.170 回答
3

您在 中创建列表的方式有误disassociate。尝试这个:

(define (disassociate lst)
  (if (null? lst)
      '()
      (cons (caar lst)
            (cons (cdar lst) 
                  (disassociate (cdr lst))))))

或者,使用list*

(define (disassociate lst)
  (if (null? lst)
      '()
      (list* (caar lst)
             (cdar lst) 
             (disassociate (cdr lst)))))

上面假设关联列表cons用于将值粘在一起,注意输出列表是如何cons通过第一个元素创建的,然后是第二个元素,然后调用递归。另一方面,如果关联列表是list用来将值粘在一起的,那么这是解除关联的方法:

(define (disassociate lst)
  (if (null? lst)
      '()
      (cons (caar lst)
            (cons (cadar lst) ; here's the change
                  (disassociate (cdr lst))))))

或者:

(define (disassociate lst)
  (if (null? lst)
      '()
      (list* (caar lst)
             (cadar lst) ; here's the change
             (disassociate (cdr lst)))))

更惯用的解决方案是使用高阶过程来处理输入列表。以下是如何使用foldr问题中描述的两个关联列表变体:

; associations created with cons
(define (disassociate lst)
  (foldr (lambda (pr ac) (list* (car pr) (cdr pr) ac))
         '()
         lst))

; associations created with list
(define (disassociate lst)
  (foldr (lambda (pr ac) (list* (car pr) (cadr pr) ac))
         '()
         lst))
于 2013-09-10T15:10:00.400 回答