【问题标题】:How to mimic something like "set intersection" and "set union" with Clojure(Script) strings?如何用 Clojure(Script) 字符串模仿“设置交集”和“设置联合”之类的东西?
【发布时间】:2016-04-24 23:50:54
【问题描述】:

假设S和T是分别定义如下的字符串:

;; S
A
B
C

;; T
B
C
D

是否存在满足以下条件的类似 clojure(script) 操作 string-intersection 和 string-union(因为没有更好的名称)?

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

和

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

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

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

【问题讨论】:

  • 你应该能够在大多数语言中实现这两个函数,方法是将两个字符串分成几行,对它们进行排序(如果它们是无序的)并合并。两个函数的合并策略只是不同。

标签: string clojure clojurescript set-theory


【解决方案1】:

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

要使用集合,您可以使用 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"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-09-01
    • 2023-03-21
    • 1970-01-01
    • 1970-01-01
    • 2011-06-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多