【发布时间】:2013-05-27 17:44:36
【问题描述】:
这是处理带有重复元素的单个列表的 nieve 案例,我在处理一些嵌套列表时遇到了麻烦,所以我想先写一个简单的案例。 所以我有:
(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 (rest listOfElements) (list l e) (first 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
那行有什么问题?
【问题讨论】:
-
哦,哎呀,那个 lise 应该是:(packDuplicatesIntoLists (rest listOfElements) (list l e) (list (first listOfElements))),第三个 arg 假定是一个列表
-
所以没关系:}
-
(defn packDuplicatesIntoLists [listOfElements l e] (if(= '() listOfElements) (if (= e '()) l (cons e l) ) (if (= (first listOfElements) (first e ) ) (packDuplicatesIntoLists (rest listOfElements) l (cons (first listOfElements) e)) (packDuplicatesIntoLists (rest listOfElements) (con e l) (list (first listOfElements))) ) ) (packDuplicatesIntoLists '(2 2 2 4 4 4 5 5 5 8 8 8 6 9 9 9) '() '()) ((9 9 9) (6) (8 8 8) (5 5 5) (4 4 4) (2 2 2) s())