This page is not created by, affiliated with, or supported by Slack Technologies, Inc.
2023-09-13
Channels
- # announcements (15)
- # babashka (48)
- # beginners (5)
- # biff (4)
- # calva (3)
- # cider (10)
- # clerk (16)
- # clj-kondo (6)
- # cljdoc (20)
- # cljs-dev (13)
- # clojure (117)
- # clojure-argentina (1)
- # clojure-brasil (5)
- # clojure-europe (40)
- # clojure-nl (1)
- # clojure-norway (111)
- # clojure-uk (5)
- # clojurescript (16)
- # cursive (20)
- # datascript (2)
- # datomic (106)
- # etaoin (2)
- # events (3)
- # funcool (1)
- # graphql (1)
- # helix (8)
- # hyperfiddle (36)
- # leiningen (12)
- # matrix (1)
- # nrepl (1)
- # off-topic (61)
- # other-languages (10)
- # polylith (22)
- # practicalli (1)
- # reagent (28)
- # reitit (11)
- # remote-jobs (3)
- # ring (12)
- # shadow-cljs (109)
- # slack-help (6)
- # solo-full-stack (23)
- # squint (7)
- # xtdb (11)
Is there a better strategy than what I've got here for partitioning a collection with a predicate?
(let [xs [:a 1 2 3 4 5 :b 6 :c 7 8 9]]
(into [] (comp (partition-by keyword?)
(partition-all 2)
(map (partial apply into)))
xs))
;; [[:a 1 2 3 4 5] [:b 6] [:c 7 8 9]]
That usually works. But read here (disclaimer: it's by me) for more detail: https://www.juxt.pro/blog/new-medley-partition-fns/
👀 1
I think a question would come down to 'better in what way'? with the provided strategy, if the vector doesn't start with a keyword, then the outcome is sort of the reverse of what I think is desired:
(let [xs [0 :a 1 2 3 4 5 :b 6 :c 7 8 9]]
(into [] (comp (partition-by keyword?)
(partition-all 2)
(map (partial apply into)))
xs))
=> [[0 :a] [1 2 3 4 5 :b] [6 :c] [7 8 9]]
Another different approach besides the above would be to find the indexes that match the pred and then subvec them:
(let [t [0 :a 1 2 3 4 5 :b 6 :c 7 8 9]]
(->> (keep-indexed #(when (keyword? %2) %1) t)
(partition-all 2 1)
(map #(apply subvec t %))))
=> ([:a 1 2 3 4 5] [:b 6] [:c 7 8 9])
This drops elements before the first keyword, which might be desired or undesired; this is just a thrown together example that could be tweaked as desired👍 1
@UE1N3HAJH ahh not an uncommon problem then, cool. love medley. at least im not missing something obvious