Fork me on GitHub
#clojure-nl
<
2022-04-26
>
Thierry07:04:27

Can someone explain how take-nth works? I get how (take-nth 3 (range 10)) returns (0 3 6 9), but why does (take-nth 3 [1 2 3]) return (1) and not (3)?

Thierry07:04:18

Is it because take-nth always starts at 0 no matter what number you enter?

Thierry07:04:44

and since [1 2 3] does not contain a 3rd item it only returns the 1st, e.g. 0?

Mno07:04:36

yes! to most of your questions here's a gist of how of take-nth works:

(lazy-seq
      (when-let [s (seq coll)]
        (cons (first s) (take-nth n (drop n s)))))
partially copied from the proper source code here : https://github.com/clojure/clojure/blob/clojure-1.10.1/src/clj/clojure/core.clj#L4288

Mno07:04:18

so basically it checks if there's anything left Takes the first value of that collection, and cons' the result of take-nth with a collection which will have it's n first bits dropped off. (which will make the next number you want the first in line and so forth)

Mno07:04:24

which also means that for n < 1 it will constantly give you the first val in the collection.

Thierry07:04:06

right, that explains it for me, thanks!

vijaykiran07:04:05

“Returns lazy seq of every nth item in coll”. - key word here is every

Thierry07:04:17

Thanks, every indeed

vijaykiran07:04:19

user=> (take-nth 3 [1 2 3])
(1)
user=> (take-nth 3 [1 2 3 4])
(1 4)
user=> (take-nth 3 [1 2 3 4 5])
(1 4)
user=> (take-nth 3 [1 2 3 4 5 6])
(1 4)
user=> (take-nth 3 [1 2 3 4 5 6 7])
(1 4 7)
user=> (take-nth 3 [1 2 3 4 5 6 7 8])
(1 4 7)
user=> (take-nth 3 [1 2 3 4 5 6 7 8 9])
(1 4 7)
user=> (take-nth 3 [1 2 3 4 5 6 7 8 9 0])
(1 4 7 0)

🙌 1
Ruben.Hamers07:04:49

@vijaykiran It is a morning to be good on btw 😉

😅 1