如何分组数据集(元组)并获得它的属性值的总和?

时间:2016-05-21 01:07:04

标签: clojure datomic

基本上我想获得包含交易(地图列表)的地图,这些交易分组为交易,纸张,回测键的集合。

我不确定该怎么做,所以我在下面做了一个疯狂的猜测。

我想要做的是获取每个交易(实体)的余额(交易,纸张,回测)。

(def results types-of-accounts)

(def trading-tx-collection (results :trading))
(def backtest-tx-collection (results :backtest))
(def paper-tx-collection (results :paper))

(def trading-total-balance (get-total-balance trading-tx-collection))
(def backtest-total-balance (get-total-balance backtest-tx-collection))
(def paper-total-balance (get-total-balance paper-tx-collection))

(def grand-total (+ trading-total-balance backtest-total-balance paper-total-balance))


(defn get-total-balance
  "calculates total balance of all transactions"
  [account-type-collection]
  (reduce + (map :balance :account/balance account-type-collection)))

;; should return {:trading [[entity map] [entity map] [entity map]]
;;                :paper [[entity map] [entity map] [entity map]]
;;                :backtest [[entity map] [entity map] [entity map]]}
;; where a [entity map] looks like [:accounting/type "Trading :accounting/balance 300]
(defn types-of-accounts
  "Get a map of entities grouped into one of 3 account types: TRADING PAPER BACKTEST"
  [user]
  (initialize-db)
  (let
    [conn (d/connect uri)]
    (pull db '[:trading (:account/trading) :paper (:account/paper) :backtest (:accounting/backtest)]
      (q '[:find ?e
           :in $ ?user
           :where
           [?e :account/user ?user]]
         (d/db conn)
         user))))

1 个答案:

答案 0 :(得分:1)

我编写了一些示例数据并对其做了一些假设,所以我希望这仍然有用作为一个例子。如果您包含样本输入

accounting> (def transcations [[:accounting/type "Trading :accounting/balance 300"]
                               [:accounting/type "Trading :accounting/balance 300"]
                               [:accounting/type "Paper :accounting/balance 300"]
                               [:accounting/type "Paper :accounting/balance 100"]
                               [:accounting/type "Paper :accounting/balance 300"]
                               [:accounting/type "Backtest :accounting/balance 300"]])
#'accounting/transcations
accounting> (->> transcations
                 (map second)
                 (map #(clojure.string/split % #" "))
                 (map #(hash-map (keyword (first %)) (Integer. (nth % 2))))
                 (apply merge-with +))

有趣的部分是在最后一行调用merge-with。