getting the positions of the occurrences of one item in a sequence

谁说我不能喝 提交于 2019-12-12 04:16:07

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!