Barış Can Ateş
Barış Can Ateş

Reputation: 334

Working on nested vector of vectors - Clojure


(def order-info-query
  (->> (d/q
         '[:find ?si ?ia ?os ?p
           :where
           [?e :proposal/id _]
           [?e :proposal/supplier-id ?s]
           [?e :proposal/item-amount ?ia]
           [?e :proposal/amount ?p]
           [?e :proposal/order-status ?ps]
           [?s :company/brand-name ?si]
           [?ps :db/ident ?os]
           ]
         db)
       )
  )

My query output doesn't have unit prices, so I needed to calculate them and return new data included with unit prices.

(identity order-info-query)
;=>
;[["IBM" 10 :order-status/ongoing 110000]
; ["apple" 20 :order-status/waiting 239000]
; ["HP" 10 :order-status/ongoing 119000]]

Hello, I wanted to find unit prices and sort those prices from cheaper to expensive. That is my code, I wonder if there is any easier or tricky way to do that?

(sort-by last (mapv (fn [x] (let [[n c v b] x] (conj [] n c v b  "Unit price:" (/ b c)))) order-info-query))
;=>
;(["IBM" 10 :order-status/ongoing 110000 "Unit price:" 11000]
; ["HP" 10 :order-status/ongoing 119000 "Unit price:" 11900]
; ["apple" 20 :order-status/waiting 239000 "Unit price:" 11950])

Upvotes: 0

Views: 73

Answers (1)

James Elliott
James Elliott

Reputation: 1017

Your order info vectors are starting to get long enough that it may be a better idea to use maps so the values have keys that explain what they are, and then you’d just be adding a new key/value to each map.

But before even doing that you can simplify your anonymous function that adds the unit price text and value. Instead of (conj [] n c v b …) you can use (conj x …). Then you no longer need to destructure n or v: (let [_ c _ b] …)

Upvotes: 2

Related Questions