Share your thoughts in the 2025 State of Clojure Survey!

Welcome! Please see the About page for a little more info on how this works.

+1 vote
ago in Beginner by
edited ago by

I'm trying to define a function that will extract a shorter vector from a longer vector. Here is the code:

(defn vfromv [v1 v2 start stop] 
    (loop [i start] 
      (if (> i stop)
        "Stop-val exceeded"
          (do
            (conj v2 (get v1 i))
            (println i)
            (println (get v1 i))
            (if (> i 0) (println (get v2 i)))
            (println v2)
            (recur (inc i))))))

Calling the function:
(vfromv [0 1 2 3 4 5 6 7 8 9] [] 2 6)

gives the repl output:
2
2
nil
[]
3
3
nil
[]
4
4
nil
[]
5
5
nil
[]
6
6
nil
[]
"Stop-val exceeded"

It looks like the conj function isn't working but I can't see why.

Can anyone help me understand why this isn't working?

Thanks.

ago by
The second argument you passed, `[]`, is immutable. The `conj` function does not work the way you think it does.

I think you're looking for `subvec`, like,
    
    user> (subvec [0 1 2 3 4 5 6 7 8 9] 2 7)
    [2 3 4 5 6]

1 Answer

0 votes
ago by
edited ago by
 
Best answer

Thanks Harold. I see.

For others coming here Harolds comment above is the answer (I don't know how to select it as the answer directly).

ago by
you got it, (:
...