partial unique?

Q&A's, tips, howto's
Locked
tom
Posts: 168
Joined: Wed Jul 14, 2004 10:32 pm

partial unique?

Post by tom »

How can I remove all duplicates from a list except one?

(111222333) becomes (12333) or whatever...

HPW
Posts: 1390
Joined: Thu Sep 26, 2002 9:15 am
Location: Germany
Contact:

Post by HPW »

Is this a list with sepearate one-digit integers?

Code: Select all

(unique '(2 3 4 4 6 7 8 7))  → (2 3 4 6 7 8)
Hans-Peter

tom
Posts: 168
Joined: Wed Jul 14, 2004 10:32 pm

Post by tom »

its strings, and I want to keep specified duplicates.

("name" "name" "name" "nobody" "nobody" "nobody")

to

("name" "nobody" "nobody" "nobody")

cormullion
Posts: 2038
Joined: Tue Nov 29, 2005 8:28 pm
Location: latiitude 50N longitude 3W
Contact:

Post by cormullion »

Hi Tom. That's a rather quirky task, so I think you might have to write a bit more code. The exact answer might depend on whether you want to keep elements in the same order, etc.

Here's a simple list traversal:

Code: Select all

(set 'l '("name" "name" "name" "nobody" "nobody" "nobody"))

(set 'keeplist '("nobody"))

(dolist (e l)
   (if (find e keeplist) 
       (push e results -1))
   (unless (find  e results)
       (push e results -1)))

;-> ("name" "nobody" "nobody" "nobody")
A non-iterative solution is easy too:

Code: Select all

(define (keep? e) (find e '("nobody"))) ; 
(append (unique (clean keep? l)) (filter keep? l)) 
which returns the same thing.

Locked