2011-11-19 40 views
3

移动项目我有这样的名单:Clojure的:在一个列表

("a" "b" "c" "d" "e") 

我想在第一个位置移动“d”:

("d" "a" "b" "c" "e") 

有没有什么简单的方法来做到这一点?

编辑

感谢您的回答。我有一个看看它,我做到了这一点:

(defn move-item [data item-to-move] 
    (conj (remove #(= % item-to-move) data) item-to-move)) 
(move-item ["a" "b" "c" "d" "e"] ["d"]) 

我不知道这是不错的设计,但它的确有窍门。

+0

在这种情况下,你应该发布自己的答案,并接受它。 – 4e6

+0

(move-item [“a”“b”“c”“d”“e”] [“d”]); =>([“d”]“a”“b”“c”“d”“ E“) – BLUEPIXY

回答

1

如果您并不需要太多的灵活性,然后我会去一个解构的解决方案:

user=> (letfn [(des [{:strs [a b c d]}] [d a b c])] 
     (des (set ["a" "b" "c" "d"]))) 
["d" "a" "b" "c"] 
user=> 

使用set允许使用的元素作为键,它可以拆开使用:strs命名指示。然后你只需按照你想要的顺序返回元素。

我想一个宏应该允许你概括的方法。

5

功能,可以会有所帮助:

user=> (defn rotate [xs] (cons (last xs) (drop-last xs))) 
#'user/rotate 
user=> (rotate '(1 2 3)) 
(3 1 2) 

2. replace

user=> (replace {1 4} [1 2 3 4]) 
[4 2 3 4] 
0
(defn move-last [coll] 
    (cons (last coll) (drop-last coll))) 

user=>(move-last '("a" "b" "c" "d")) 
("d" "a" "b" "c")