[英]Clojure For loop index numbers
我怎樣才能在這段代碼中得到這個 for 循環的索引:
(def numbers [:one :two :three :four :five])
(def colors [:green :red :blue :pink :yellow])
(def letters [:A :B :C :D :E])
(for [x numbers
i colors
j letters]
(println (str x " - " i " - " j)))
此代碼將打印 125 行,我希望每一行都有索引號。
你需要map-indexed
:
(def numbers [:one :two :three :four :five])
(def colors [:green :red :blue :pink :yellow])
(def letters [:A :B :C :D :E])
(->> (for [x numbers
i colors
j letters]
(str x " - " i " - " j))
(map-indexed (fn [index value]
(str "Index: " index " : " value)))
(run! println))
(fn [index value]...)
的較短版本:
(map-indexed #(str "Index: " %1" : " %2))
還可以考慮用一個長字符串調用一個println
而不是調用 125x println
,它似乎更快:
(->> (for [x numbers
i colors
j letters]
(str x " - " i " - " j))
(map-indexed #(str "Index: " %1 " : " %2 "\n"))
str/join
println)
( str/join
是clojure.string/join
)
Clojure 不鼓勵使用原子,但我認為這是最簡單的方法:
(let [index (atom 0)]
(for [x numbers
i colors
j letters]
(do (swap! index inc)
(println (str @index ": " x " - " i " - " j)))))
有很多選擇。 這里有一些:
(ns tst.demo.core
(:use demo.core tupelo.core tupelo.test)
(:require
[clojure.string :as str]
[tupelo.core :as t]
))
(def numbers [:one :two :three :four :five])
(def colors [:green :red :blue :pink :yellow])
(def letters [:A :B :C :D :E])
(verify
; The tupelo.core/indexed function will add a 0-based index to each element in a sequence
(is= (t/indexed [:a :b :c])
[[0 :a]
[1 :b]
[2 :c]]))
tupelo.core/indexed
function 將為序列中的每個元素添加一個從 0 開始的索引,這通常很方便。
(verify
; tupelo.core/map-let allows you to assign a local name to each item from multiple sequences
; but behaves like `map`, not `for`
(let [vecs (t/map-let [n numbers
c colors
l letters]
[n c l]) ; return a vector containing each item in sequence
]
(is= vecs
[[:one :green :A]
[:two :red :B]
[:three :blue :C]
[:four :pink :D]
[:five :yellow :E]])))
使用t/map-let
允許您為每個序列的元素指定一個本地名稱,但不會像for
那樣創建笛卡爾積。
(verify
(t/let-spy-pretty ; or just `let` to suppress the "spy" printing
[
; using (mapv vector ...) will also place each triple into a vector
vecs (mapv vector numbers colors letters)
strs (mapv #(str/join " - " %) vecs)
strs-idx (t/indexed strs)
lines (t/forv [[the-idx the-str] strs-idx]
(str the-idx ": " the-str))]
(is= vecs
[[:one :green :A]
[:two :red :B]
[:three :blue :C]
[:four :pink :D]
[:five :yellow :E]])
(is= strs
[":one - :green - :A"
":two - :red - :B"
":three - :blue - :C"
":four - :pink - :D"
":five - :yellow - :E"])
(is= strs-idx
[[0 ":one - :green - :A"]
[1 ":two - :red - :B"]
[2 ":three - :blue - :C"]
[3 ":four - :pink - :D"]
[4 ":five - :yellow - :E"]])
(is= lines
["0: :one - :green - :A"
"1: :two - :red - :B"
"2: :three - :blue - :C"
"3: :four - :pink - :D"
"4: :five - :yellow - :E"])))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.