This page is not created by, affiliated with, or supported by Slack Technologies, Inc.
2022-04-26
Channels
- # babashka (7)
- # beginners (85)
- # calva (39)
- # cider (3)
- # clara (1)
- # clj-kondo (10)
- # clojure (194)
- # clojure-europe (36)
- # clojure-madison (2)
- # clojure-nl (13)
- # clojure-spec (11)
- # clojure-uk (2)
- # clojurescript (17)
- # community-development (5)
- # component (9)
- # conjure (4)
- # core-async (3)
- # cursive (32)
- # data-science (26)
- # datomic (31)
- # graalvm (22)
- # holy-lambda (31)
- # honeysql (7)
- # introduce-yourself (1)
- # jobs (9)
- # jobs-rus (1)
- # lsp (3)
- # malli (9)
- # off-topic (54)
- # pathom (27)
- # pedestal (6)
- # portal (1)
- # re-frame (4)
- # releases (1)
- # remote-jobs (1)
- # sci (3)
- # shadow-cljs (4)
- # spacemacs (13)
- # vim (14)
- # xtdb (3)
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)
?
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#L4288so 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)
which also means that for n < 1 it will constantly give you the first val in the collection.
“Returns lazy seq of every nth item in coll”. - key word here is every
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