我的矢量看起来像:
[ "1" "2" "3" "4" ]
我希望写一个函数将向量返回到:
[ 1 "2" 3 4 ]
; Note that the second element is still a string
请注意,没有任何更改,将返回一个全新的向量。在clojure中最简单的方法是什么?
答案 0 :(得分:5)
map-indexed是一个不错的选择。调用您传递的函数,其中包含输入项之一的值和找到它的索引(索引优先)。该函数可以选择生成新值或返回现有值。
user> (map-indexed (fn [i v]
(if-not (= 1 i)
(Integer/parseInt v)
v))
[ "1" "2" "3" "4"])
(1 "2" 3 4)
当if
返回v时,它与结果地图中的值完全相同,因此您可以在选择保留的部分中保留结构共享的好处。如果您希望将输出保存为向量,则可以使用mapv并传递自己的索引序列。
user> (mapv (fn [i v]
(if-not (= 1 i)
(Integer/parseInt v)
v))
(range)
[ "1" "2" "3" "4"])
[1 "2" 3 4]
有很多方法可以写这个
答案 1 :(得分:1)
我将如何做到这一点。请注意,索引从零开始:
(defn map-not-nth
"Transform all elements of coll except the one corresponding to idx (zero-based)."
[func coll idx]
{:pre [ (<= 0 idx (count coll)) ]
:post [ (= (count %) (count coll))
(= (nth coll idx) (nth % idx) ) ] }
(let [coll-tx (map func coll) ; transform all data
result (flatten [ (take idx coll-tx) ; [0..idx-1]
(nth coll idx) ; idx
(drop (inc idx) coll-tx) ; [idx+1..N-1]
] ) ]
result ))
(def xx [ 0 1 2 3 4 ] )
(prn (map-not-nth str xx 0))
(prn (map-not-nth str xx 1))
(prn (map-not-nth str xx 2))
(prn (map-not-nth str xx 3))
(prn (map-not-nth str xx 4))
结果是:
user=> (prn (map-not-nth str xx 0))
(0 "1" "2" "3" "4")
user=> (prn (map-not-nth str xx 1))
("0" 1 "2" "3" "4")
user=> (prn (map-not-nth str xx 2))
("0" "1" 2 "3" "4")
user=> (prn (map-not-nth str xx 3))
("0" "1" "2" 3 "4")
user=> (prn (map-not-nth str xx 4))
("0" "1" "2" "3" 4)