Reputation: 99
I would like to loop through a vector starting from the nth element not 0;
How it looks like in Java:
for(int i = firstIndex; i <= lastIndex; i++) {
newText += contents[i] + " ";
}
Upvotes: 0
Views: 579
Reputation: 5766
If you are always dealing with a vector, then subvec
is a good choice. For example:
(subvec contents firstIndex)
If you want to be compatible with sequences in general, you'll want to use drop
. drop
is O(n)
w.r.t. the number of elements dropped, which subvec
is always O(1)
. If you're only ever dropping a few elements, the difference is negligible. But for dropping a large number of elements (i.e., large firstIndex
), subvec
will be a clear winner. But subvec
is only available on vectors.
Upvotes: 5
Reputation: 8100
You can use the drop
function to skip first n
elements and then loop over the result. For example, if you want to skip two first elements:
user=> (drop 2 [1 2 3 4])
(3 4)
The following can possibly do the same that the Java form you provided:
(require '[clojure.string :as str])
(str/join " " (drop first-index contents))
Upvotes: 1