Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Suggested addition: index-of #54

Open
orestis opened this issue Jun 8, 2021 · 3 comments
Open

Suggested addition: index-of #54

orestis opened this issue Jun 8, 2021 · 3 comments

Comments

@orestis
Copy link

orestis commented Jun 8, 2021

The humble indexOf -> you have a known small vector or sequence, you are doing ops on it and you want to find a particular element's index. (Because you have to e.g. replace it later, or put something before or after it).

Naive implementation:

(defn index-of
  "Return the first index of x inside a seq of xs, or nil"
  [xs x]
  (->> xs
       (medley/indexed)
       (medley/find-first (fn [[_idx item]]
                            (= item x)))
       (first)))
@borkdude
Copy link
Contributor

borkdude commented Jun 8, 2021

If you already have a vector, you can just use .indexOf in the implementation, for performance.

@orestis
Copy link
Author

orestis commented Jun 8, 2021

True, if you know what you have. But .indexOf will also use identical? instead of =, right? This might be a reason to add this more generic index-of -- if someone needs absolute performance they would stick with vectors and use .indexOf. In any case, this is more a convenience (for me) when manipulating very small vectors (e.g. up to 10 items)

@borkdude
Copy link
Contributor

borkdude commented Jun 8, 2021

@orestis I don't think it does:

https://github.com/clojure/clojure/blob/master/src/jvm/clojure/lang/APersistentVector.java#L186-L191

I mean, if you're going to implement this as part of this library, it's fairly cheap to check vector? first and then call this, and for other cases fall back on the seq behavior.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants