2013-01-03 30 views
1

我不實用的風格太精通,我不希望使用任何設置功能,所以我有一個問題。我真的很掙扎,我是否應該遞歸或以不同的方式做。添加基於它的對兩個或兩個以上名單列表中的

我有對集合中的一個列表中,像這樣:

((4 2) (3 1) (3 2) (2 4) etc...) 

在該一對「(4 2),該第二元件‘2’告訴哪個其他對它比賽我於在這種情況下'(3 2)。 所以,我添加了這兩對一起使用他們的第一個元素,在這種情況下,它的「4」和「3」。 新對現在是'(7 2)。等在名單太其他對。 最後,它應該返回:

((7 2) (3 1) (2 4)) 

我不太關心的順序。 。 我已經有一個工作函數,添加兩個不同的對。這個函數的唯一假設是這些對是匹配的。

因此,我想要做的是操縱對這個列表返回以這些方式的列表。

例子:

take the list ((4 2) (3 1) (3 2) (2 4))  
matching-pairs: '(4 2) and '(3 2) 

and then return --> ((7 2) (3 1) (2 4)) 


take the list ((2 1) (3 2) (1 2) (5 1) (6 3)) 
matching-pairs: '(2 1) and '(5 1) 
       '(3 2) and '(1 2) 

and then return --> ((7 1) (4 2) (6 3)) 

謝謝您的時間和精力。

+0

你有什麼這麼遠嗎? –

回答

3

遍歷列表,並存儲每個看起來像這樣的對的car到列表中的assoc

original: ((2 . 1) (3 . 2) (1 . 2) (5 . 1) (6 . 3)) 
new:  ((1 . (2 5)) 
      (2 . (3 1)) 
      (3 . (6)) 

再總結所有的cdr小號一起翻轉每一對得到這個:

  ((7 . 1) (4 . 2) (6 . 3)) 
+0

這看起來很不錯。您是否也可以簡要介紹一下,如您所說,在「聯合」中創建新列表?我是功能風格的新手,我的思維不斷轉向程序風格。 – jbchichoko

+0

關聯列表的細節可以[點擊這裏]研究發現(https://www.cs.cmu.edu/Groups/AI/html/cltl/clm/node153.html)。基本上,你想先通過源列表並從中創建alist(提示:使用'map')。您可能需要新增的項目,作爲你去,或者你可能希望把他們都在一個列表,nooodl建議。然後,如果您之前沒有這樣做,則可以將它們相加,然後將數據轉換回您需要的任何結構。 – zck

1
(defun get-pairs (alist index) 
    (cond 
    (alist 
    (if (= (nth 1 (car alist)) index) 
     (append (list (caar alist)) (get-pairs (cdr alist) index)) 
     (get-pairs (cdr alist) index))) 
    ((not alist) 
    'nil))) 


(defun get-iterator (alist) 
    (labels 
    ((f (alist res) 
     (cond 
      (alist 
      (if (member (nth 1 (car alist)) res) 
       (f (cdr alist) res) 
       (f (cdr alist) (append (cdar alist) res)))) 
      ((not alist) 
      res)))) 
    (f alist 'nil))) 


(defun get-value (alist) 
    (loop for i in (get-iterator alist) 
     collect (get-pairs alist i))) 

(defun list-sum (alist) 
    (loop for i in (get-value alist) 
     collect (apply #'+ i))) 

(defun match-value (alist) 
    (loop for i in (get-iterator alist) 
     for j in (list-sum alist) 
     collect (append (list j) (list i)))) 


(defparameter *my-list* '((2 1) (3 1) (4 2) (5 2) (8 1) (9 2) (1 3) (0 3))) 

(print (match-value *my-list*)) 

對不起,亂碼,但如果我明白問題的權利應該做的伎倆。

相關問題