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


suppose s , t strings defined respectively follows:

;; s b c  ;; t b c d 

are there analogous clojure(script) operations string-intersection , string-union (for lack of better name) satisfy following?

(string-intersection s t) ;; =>  ;; b ;; c 

and

(string-union s t) ;; =>  ;; ;; b ;; c ;; d 

as can see, string-intersection eliminate (on line-by-line basis) non-matching lines (leaving lines match), while string-union has effect of combining lines , ignoring duplicates.

note: i'm using clojurescript, imagine answer generalize clojure well.

from description seems treat strings set of lines , calculate set intersection , union.

for working sets, can use clojure.set namespace.

first convert strings set of lines:

(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))) 

then can calculate union , intersection:

(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"} 

and sort it:

(def s-t-union-sorted (sort s-t-union)) ;; => ("a" "b" "c" "d")  (def s-t-intersection-sorted (sort s-t-intersection)) ;; => ("b" "c") 

you can convert string of lines:

(str/join "\n" s-t-union-sorted) ;; => "a\nb\nc\d"  (str/join "\n" s-t-intersection-sorted) ;; => "b\nc" 

Comments

Popular posts from this blog

javascript - How to get current YouTube IDs via iMacros? -

c# - Maintaining a program folder in program files out of date? -

emulation - Android map show my location didn't work -