How to remove multiple items from a list?

I have a list [2 3 5] that I want to use to remove items from another list, for example [1 2 3 4 5], so that I get [1 4].

thanks

+6
clojure
source share
4 answers

Try the following:

(let [a [1 2 3 4 5] b [2 3 5]] (remove (set b) a)) 

which returns (1 4) .

The remove function, by the way, takes a predicate and a collection and returns a sequence of elements that do not satisfy the predicate (the set in this example).

+17
source share
 user=> (use 'clojure.set) nil user=> (difference (set [1 2 3 4 5]) (set [2 3 5])) #{1 4} 

Link:

+5
source share

You can do it yourself with something like:

 (def a [2 3 5]) (def b [1 2 3 4 5]) (defn seq-contains? [coll target] (some #(= target %) coll)) (filter #(not (seq-contains? a %)) b) ; (3 4 5) 

A version based on the reducers library can be:

 (require '[clojure.core.reducers :as r]) (defn seq-contains? [coll target] (some #(= target %) coll)) (defn my-remove "remove values from seq b that are present in seq a" [ab] (into [] (r/filter #(not (seq-contains? b %)) a))) (my-remove [1 2 3 4 5] [2 3 5] ) ; [1 4] 

EDIT Added seq-contains? the code

+1
source share

Here is my trick without using kits;

 (defn my-diff-func [XY] (reduce #(remove (fn [x] (= x %2)) %1) XY )) 
0
source share

All Articles