问题
From a a sequence, I need to fetch all the positions of the occurrence of a given item.
I'm asking myself if this is a good way to solve the problem:
(defn get-positions [item coll]
(->> (map-indexed vector coll)
(filter (fn [[_ v]] (= item v)))
(map first)))
This also works for strings, they'll be transformed to a sequence by the first map. However, if I know the input's are strings, would there be a more string specific approach for this problem?
回答1:
Since you already have a general solution to the problem, why would you want to spend more effort to try to come up with a more specific one? The benefits of doing so here are negligible.
Just for variety's sake, here's another way to implement your function:
(defn positions [x coll]
(keep-indexed #(when (= x %2) %1) coll))
来源:https://stackoverflow.com/questions/35470950/getting-the-positions-of-the-occurrences-of-one-item-in-a-sequence