Clojure: Destructuring Group-by's Output
Join the DZone community and get the full member experience.
Join For FreeOne of my favourite features of Clojure is that it allows you to destructure a data structure into values that are a bit easier to work with.
I often find myself referring to Jay Fields’ article which contains several examples showing the syntax and is a good starting point.
One recent use of destructuring I had was where I was working with a vector containing events like this:
user> (def events [{:name "e1" :timestamp 123} {:name "e2" :timestamp 456} {:name "e3" :timestamp 789}])
I wanted to split the events in two – those containing events with a timestamp greater than 123 and those less than or equal to 123.
After remembering that the function I wanted was group-by and not partition-by (I always make that mistake!) I had the following:
user> (group-by #(> (->> % :timestamp) 123) events) {false [{:name "e1", :timestamp 123}], true [{:name "e2", :timestamp 456} {:name "e3", :timestamp 789}]}
I wanted to get 2 vectors that I could pass to the web page and this is fairly easy with destructuring:
user> (let [{upcoming true past false} (group-by #(> (->> % :timestamp) 123) events)] (println upcoming) (println past)) [{:name e2, :timestamp 456} {:name e3, :timestamp 789}] [{:name e1, :timestamp 123}] nil
Simple!
Published at DZone with permission of Mark Needham, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Trending
-
Building a Flask Web Application With Docker: A Step-by-Step Guide
-
Managing Data Residency, the Demo
-
Why You Should Consider Using React Router V6: An Overview of Changes
-
What Is React? A Complete Guide
Comments