2013-05-27 51 views
-1

這是處理單個列表的重複元素的小問題,我正在處理一些處理一些嵌套列表的結,所以我想寫首先是簡單情況。 所以我有:99 Clojure中的第9個問題(將列表元素的連續副本包裝到子列表中)

(defn packDuplicatesIntoLists [listOfElements l e] 
     (if(= e 'nil) 
     'true 
     (if(=() listOfElements) 
      (if 
      (= e '()) 
      l 
      (list l e) 
     ) 
      (if 
       (= (first listOfElements) (first e)) 
       (packDuplicatesIntoLists (rest listOfElements) l (cons (first listOfElements) e)) 
     (packDuplicatesIntoLists (rest listOfElements) (list l e) (first listOfElements)) 
     ) 
     ) 

) )

(packDuplicatesIntoLists '(2) '(1 1) '(2 2)) (packDuplicatesIntoLists '() '(1 1) '(2 2)) (packDuplicatesIntoLists '() '() '()) (packDuplicatesIntoLists '(1 1 1 2 2 2 3 3 3 4 4 4 4) '() '()) 

但 (packDuplicatesIntoLists(休息listOfElements)(名單LE)(第一listOfElements)) 是讓我陷入麻煩,

#'NintyNineProblems.LearnSpace/packDuplicatesIntoLists 
    ((1 1) (2 2 2)) 
    ((1 1) (2 2)) 
    () 
    IllegalArgumentException Don't know how to create ISeq from: java.lang.Long clojure.lang.RT.seqFrom (RT.java:505 

這條線怎麼了?

+0

哦,哎呀,莉莎應該是:(packDuplicatesIntoLists(休息listOfElements)(名單LE)( list(first listOfElements))),第三個參數被假定爲一個列表 – jwilson

+0

所以它的工作原理:} – jwilson

+0

(defn packDuplicatesIntoLists [listOfElements le] (if(='()lis tOfElements) (如果 (= E「()) 升 (利弊EL) ) (如果 (=(第一listOfElements)(第一E)) (packDuplicatesIntoLists(休息listOfElements)L(利弊(第一listOfElements情況)e)) (packDuplicatesIntoLists(休息listOfElements)(利弊EL)(列表(第一listOfElements))) ) ) ) (packDuplicatesIntoLists「(2 2 2 4 4 4 5 5 5 8 8 8 6 9 9 9)9(9)(6)(8 8 8)(5 5 5)(4 4 4)(2 2 2)s()) – jwilson

回答

0

所以,它仍反轉lsit,但尾遞歸

 (defn packDuplicatesIntoLists [listOfElements l e] 
     (if(= '() listOfElements) 
     (cons e l) 
     (if 
     (= (first listOfElements) (first e)) 
     (recur (rest listOfElements) l (cons (first listOfElements) e)) 
     (if (= '() e) 
      (recur (rest listOfElements) l (list (first listOfElements))) 
      (recur (rest listOfElements) (cons e l) (list (first listOfElements))) 
     ) 
     ) 
     ) 
    ) 

(packDuplicatesIntoLists '(2 2 2 4 4 4 5 5 5 8 8 8 6 9 9 9 9 9)'()「( )) (packDuplicatesIntoLists '()'() '())(packDuplicatesIntoLists' 零 '()'())

相關問題