Outer join in Clojure

非 Y 不嫁゛ 提交于 2019-12-01 03:46:27
NielsK

Sean Devlin's (of Full Disclojure fame) table-utils has the following join types:

  • inner-join
  • left-outer-join
  • right-outer-join
  • full-outer-join
  • natural-join
  • cross-join

It hasn't been updated in a while, but works in 1.3, 1.4 and 1.5. To make it work without any external dependencies:

  • replace fn-tuple with juxt
  • replace the whole (:use ) clause in the ns declaration with (require [clojure.set :refer [intersection union]])
  • add the function map-vals from below:

either

(defn map-vals
  [f coll]
  (into {} (map (fn [[k v]] {k (f v)}) coll)))

or for Clojure 1.5 and up

(defn map-vals
  [f coll]
  (reduce-kv (fn [acc k v] (assoc acc k (f v))) {} coll))

Usage of the library is join type, two collections (two sets of maps like the example above, or two sql resultsets) and at least one join fn. Since keywords are functions on maps, usually only the join keys will suffice:

=> (full-outer-join s1 s2 :a :a)
   ({:a 1, :c 3, :b 2}
    {:a 2, :c 5, :b 3}
    {:b 8, :a 3})

If I remember correctly Sean tried to get table-utils into contrib some time ago, but that never worked out. Too bad it never got it's own project (on github/clojars). Every now and then a question for a library like this pops up on Stackoverflow or the Clojure Google group.

Another option might be using the datalog library from datomic to query clojure data structures. Stuart Halloway has some examples in his gists.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!