How can I cast a sequence back to vector after a sequence producing operation (like sort)? Does using (vec..) on a sequence that was a vector is costly?
One (bad?)
As a new Clojure developer, it is easy to confuse collections and sequences.
This sorted vector function:
(sort [1 2 3 4 5 6]) => (1 2 3 4 5 6) ; returns a sequence
But I need a vector for the next operation because this does not work...
(take-while (partial > 3) (1 2 3 4 5 6))
=>ClassCastException java.lang.Long cannot be cast to clojure.lang.IFn user/eval2251 (NO_SOURCE_FILE:2136)
Let us try to convert the sequence to a vector:
(vec (1 2 3 4 5 6))
=>ClassCastException java.lang.Long cannot be cast to clojure.lang.IFn user/eval2253 (NO_SOURCE_FILE:2139)
Nope! But if you put it all together, it works just fine.
(take-while (partial > 3) (sort [1 2 3 4 5 6]))
=>(1 2)
The lesson: You cannot work with sequences directly! They are an intermediate step in the process. When the REPL tries to evaluate (1 2 3 4 5 6), it sees a a function and throws an exception:
(1 2 3 4 5 6) =>ClassCastException java.lang.Long cannot be cast to clojure.lang.IFn user/eval2263 (NO_SOURCE_FILE:2146)