2
votes

This is a pretty basic question I bet but bit of a head-scratcher for me. I'm trying to complete this "intro to clojure" kind of problem (http://www.4clojure.com/problem/40) where I need to design my own version of the interpose function (and outputs as a vector). I did this somewhat successfully (the sequence is correct) with the following function:

(defn my-interpose[n x] (vector (interleave x (take (count x) (repeat n)))))

However, when I run it I get back a strange output -- it seems like a list inside a vector? Here is what it looks like in my REPL...

=> (my-interpose 0 [1 2 3])
[(1 0 2 0 3 0)]

Basically, I get back this sequence in parentheses (is this a list?) and then my attempt to cast it to a vector doesn't really convert it, it just seems to wrap it. I've also tried the flatten function to no avail.

Can anyone explain how to fix, or more importantly, what the nature of this phenomenon (what I'm referring to as "nested types") is and what are the best practice ways to handle it?

Also, is my result in parenthesis a list inside a vector? Or is that sequence really not a list at all?

1
solved with the help of @Chuck! final answer was this, for those who are curious (I re-ordered and added the rest bit since it wasn't meant to have the interposed character trailing or leading). (fn my-interpose[n x] (vec (rest (interleave (take (count x) (repeat n)) x)))) - jm0
Incidentally, that take is unnecessary. You could just write (vec (rest (interleave (repeat n) x))) and get the same effect. Or, with the threading operator, (-> (repeat n) (interleave x) rest vec). - Chuck

1 Answers

4
votes

This is what vector does — it takes its arguments and places them inside a vector. I think the function you wanted is vec, which takes a collection and turns it into a vector.

Incidentally, the collection inside your vector is not a list, per se, but a LazySeq.