Clojure-适用于除第n个元素以外的所有元素
我有一个向量,看起来像:Clojure-适用于除第n个元素以外的所有元素,clojure,Clojure,我有一个向量,看起来像: [ "1" "2" "3" "4" ] 我希望编写一个函数,将向量返回到: [ 1 "2" 3 4 ] ; Note that the second element is still a string 请注意,没有任何更改,将返回一个全新的向量。在clojure中最简单的方法是什么?映射索引是一个不错的选择。调用传递的函数,其中包含来自输入的某个项的值以及找到该项的索引(索引优先)。该函数可以选择生成新值或返回现有值 user> (map-indexed (f
[ "1" "2" "3" "4" ]
我希望编写一个函数,将向量返回到:
[ 1 "2" 3 4 ]
; Note that the second element is still a string
请注意,没有任何更改,将返回一个全新的向量。在clojure中最简单的方法是什么?映射索引是一个不错的选择。调用传递的函数,其中包含来自输入的某个项的值以及找到该项的索引(索引优先)。该函数可以选择生成新值或返回现有值
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]
写这篇文章有很多方法,下面是我的方法。请注意,索引是以零为基础的:
(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)