Clojure: sequence back to vector

前端 未结 4 1041
Happy的楠姐
Happy的楠姐 2021-01-01 18:33

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?)

4条回答
  •  情歌与酒
    2021-01-01 19:31

    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)

提交回复
热议问题