Версия для печати темы
Нажмите сюда для просмотра этой темы в оригинальном формате
Форум программистов > LISP > Построение подмножеств множества.


Автор: wwall 19.10.2006, 09:23
Построение подмножеств множества.
Можно ли улучшить?

(defun oneIntersect (x y)
    (cond 
        ((null x) nil)
        ((null y) nil)
        ((equal x y) nil)
        ('t (list x y))
    )
)

(defun listIntersect (x y)
    (if (null y) nil (cons (oneIntersect x (car y)) (listIntersect x (cdr y))))
)

(defun intersect (x y)
    (if (null x) nil (cons (listIntersect (car x) y) (intersect (cdr x) y)))    
)


(setq xx (list 1 2 3 4 5))

(setq yy (remove-if #'null (apply #'append (intersect xx xx))))


Автор: svg 22.10.2006, 16:13
Цитата(wwall @  19.10.2006,  09:23 Найти цитируемый пост)
Построение подмножеств множества.


Код

(defun subsets (set)
  (case (length set)
    ((0 1) (list set))
    (otherwise (let ((ss (subsets (cdr set))))
                 (cons
                  (list (car set))
                  (append
                   (mapcar
                    #'(lambda (ss)
                        (cons (car set) ss))
                    ss)
                   ss))))))


CL-USER> (subsets '(1 2 3 4))
((1) (1 2) (1 2 3) (1 2 3 4) (1 2 4) (1 3) (1 3 4) (1 4) (2) (2 3) (2 3 4)
 (2 4) (3) (3 4) (4))

Автор: _sg 24.4.2014, 19:46
как вариант:
Код

(defun sets (w)
  (if w ((lambda (r)
           (nconc r (mapcar #'(lambda (a) (cons (car w) a)) r)))
         (sets (cdr w)))
      '(nil)))

> (sets '(a b c))
(NIL (C) (B) (B C) (A) (A C) (A B) (A B C))

Powered by Invision Power Board (http://www.invisionboard.com)
© Invision Power Services (http://www.invisionpower.com)