如何用 Clojure(Script) 字符串模仿 "set intersection" 和 "set union" 之类的东西?

How to mimic something like "set intersection" and "set union" with Clojure(Script) strings?

假设ST是分别定义如下的字符串:

;; S
A
B
C

;; T
B
C
D

是否有类似的 clojure(script) 操作 string-intersectionstring-union(由于缺少更好的名称)满足以下条件?

(string-intersection S T)
;; => 
;; B
;; C

(string-union S T)
;; => 
;; A
;; B
;; C
;; D

如您所见,string-intersection 将消除(逐行)不匹配的行(只留下匹配的行),而 string-union 的效果是合并行并忽略重复项。

注意:我正在使用 clojurescript,但我想答案也会推广到 clojure。

根据您的描述,您似乎希望将字符串视为一组线并计算集合交集和并集。

要使用集合,您可以使用 clojure.set 命名空间。

首先将您的字符串转换成一组行:

(require '[clojure.string :as str]
         '[clojure.set :as set])

(def s "A\nB\nC")
(def t "B\nC\nD")

(def s-set (into #{} (str/split-lines s)))
(def t-set (into #{} (str/split-lines t)))

然后你可以计算你的并集和交集:

(def s-t-union (set/union s-set t-set))
;; => #{"C" "B" "A" "D"}

(def s-t-intersection (set/intersection s-set t-set))
;; => #{"C" "B"}

并排序:

(def s-t-union-sorted (sort s-t-union))
;; => ("A" "B" "C" "D")

(def s-t-intersection-sorted (sort s-t-intersection))
;; => ("B" "C")

您也可以将其转换回字符串:

(str/join "\n" s-t-union-sorted)
;; => "A\nB\nC\D"

(str/join "\n" s-t-intersection-sorted)
;; => "B\nC"