tags:

views:

130

answers:

3

Hi,

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

thanks

A: 

Loop through your larger list. For each item in that list compare it to the values in the list you would like to remove. If you find a match remove that item from your orginal list. When complete you would get what you are looking for.

Matt
The double loop is an O(m*n) complexity. If both lists are sorted it is quite easy to program something that will execute in O(m+n) which is way better.
Matthieu M.
+3  A: 
user=> (use 'clojure.set)
nil
user=> (difference (set [1 2 3 4 5]) (set [2 3 5]))
#{1 4}

Reference:

Ionuț G. Stan
Is there something wrong with this solution?
Ionuț G. Stan
A vector is not a set. The ordering of the vector is not preserved when you convert it to a set. If I understands the question correctly,(difference (set [9 2 3 4 5]) (set [2 3 5]))returns #{4 9} when it should return [9 4] and(difference (set [1 1 2 3 4 5]) (set [2 3 5]))should return [1 1 4] and not #{1 4}If he wanted set semantics he probably would have used a set to begin with.
Jonas
Thanks, Jonas. You're probably right about him not wanting set semantics.
Ionuț G. Stan
+5  A: 

Try this:

(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 the elements that don't satisfy the predicate (a set, in this example).

Uros Dimitrijevic