Fork me on GitHub
#beginners
<
2022-08-02
>
Anssi Kittilä07:08:29

i have a collection and i want to partition it to two colls based on if the index is divisible by 2. What is the correct/easiest way to do this?

pyry07:08:10

Well, you could for instance use map-indexed to explicitly get a sequence of [idx val] pairs, then it should be quite easy to get to the desired output.

🙌 1
pyry07:08:25

(let [xs         [0 1 2 3 4 5]
        with-index (map-indexed vector xs)]
    (-> (group-by (fn [[idx _]] (rem idx 2)) with-index)
        (update-vals #(map second %))))

🙌 1
Martin Půda07:08:54

(let [xs [0 1 2 3 4 5]]
  [(take-nth 2 xs)
   (take-nth 2 (rest xs))])

=> [(0 2 4) (1 3 5)]

🙌 2
👍 1
jumar10:08:03

The solution with take-nth is really interesting - nice reminder there's such a function 🙂 But I prefer group-by - I think it's closer to the problem description:

(let [xs [0 1 2 3 4 5]]
  (vals (group-by even? xs)))
;; => ([0 2 4] [1 3 5])

Anssi Kittilä10:08:26

Partitioning by the index of the element being even/odd

Ed11:08:15

there's also

(->> (range 10)
       (partition 2)
       (apply map vector))

🙌 1
sheluchin10:08:33

If a function has :arglists metadata, should that be considered the "main" arglist definition over the actual arglist?

Alex Miller (Clojure team)12:08:31

I don't think this is a beginners question (more #clojure or even #clojure-dev) but, yes

sheluchin13:08:48

Thanks for the response. I will ask followup questions in #clojure.

Anssi Kittilä11:08:29

I have two vec of vecs, how do I extend the subvecs into the first coll. ie.

(conj [[1 2] [3 4] [5 6]] [[2 2] [4 4]])

Martin Půda11:08:59

(concat [[1 2] [3 4] [5 6]] [[2 2] [4 4]])
=> ([1 2] [3 4] [5 6] [2 2] [4 4])

🙌 2
Anssi Kittilä11:08:55

googled with "extend" and eyeballed the cheatsheet and didnt notice that. Thanks alot!

Ed11:08:03

I'm not sure I understand what you want. Do you mean

(apply conj [[1 2] [3 4] [5 6]] [[2 2] [4 4]])
?

Ed11:08:30

ah ... you do 😉

Anssi Kittilä11:08:33

concat was the function I was looking for

Anssi Kittilä11:08:38

(reduce conj [[1 2] [3 4] [5 6]] [[2 2] [4 4]])
this didnt seem so natural

Ed11:08:12

into will do the same thing too

Ed11:08:54

(into [[1 2] [3 4] [5 6]] [[2 2] [4 4]]) will conj each element of the second list into the first (just like reduce conj

🙌 2