Wednesday, 15 February 2012

two element combinations of the elements of a list inside lisp (without duplicates) -



two element combinations of the elements of a list inside lisp (without duplicates) -

from given list in lisp, want 2 element combinations of elements of list without having duplicate combinations ( meaning (a b) = (b a) , 1 should removed)

so illustration if have list (a b c d),

i want ((a b) (a c) (a d) (b c) (b d) (c d))

assuming i'm understanding correctly, i'd utilize mapcar , friends.

(defun pair-with (elem lst) (mapcar (lambda (a) (list elem a)) lst)) (defun unique-pairs (lst) (mapcon (lambda (rest) (pair-with (car rest) (cdr rest))) (remove-duplicates lst)))

that should allow you

cl-user> (unique-pairs (list 1 2 3 4 5)) ((1 2) (1 3) (1 4) (1 5) (2 3) (2 4) (2 5) (3 4) (3 5) (4 5)) cl-user> (unique-pairs (list :a :b :c :a :b :d)) ((:c :a) (:c :b) (:c :d) (:a :b) (:a :d) (:b :d))

if you're not scared of loop, can write sec 1 more as

(defun unique-pairs (lst) (loop (a . rest) on (remove-duplicates lst) append (pair-with rest)))

instead. i'm reasonably sure loops append directive more efficient function of same name.

list lisp common-lisp combinations

No comments:

Post a Comment