summaryrefslogtreecommitdiff
path: root/list-functions-2.lisp
blob: 0bae5f3f8e17481c933bec2b900d50f006921ed7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
(export '(copy-tree assoc assoc-if assoc-if-not rassoc rassoc-if
          rassoc-if-not sublis nsublis))


(defun copy-tree (tree)
  (typecase tree
    (cons (cons (copy-tree (car cons)) (copy-tree (cdr cons))))
    (t tree)))


(defun assoc (item alist &key key test test-not)
  (setq test (or test (if test-not
                          (complement test-not)
                          (function eql))))
  (assoc-if (lambda (x) (funcall test x item))
            alist
            :key key))

(defun assoc-if (predicate alist &key key)
  (setq key (or key (function identity)))
  (cond ((endp alist) nil)
        ((funcall predicate (funcall key (caar alist)))
         (car alist))
        (t (assoc-if predicate (cdr alist) :key key))))

(defun assoc-if-not (predicate alist &key key)
  (assoc-if (complement predicate) alist :key key))


(defun rassoc (item alist &key key test test-not)
  (setq test (or test (if test-not
                          (complement test-not)
                          (function eql))))
  (rassoc-if (lambda (x) (funcall test x item))
             alist
             :key key))

(defun rassoc-if (predicate alist &key key)
  (setq key (or key (function identity))
  (cond ((endp alist) nil)
        ((funcall predicate (funcall key (cdar alist)))
         (car alist))
        (t (assoc-if predicate (cdr alist) :key key)))))

(defun rassoc-if-not (predicate alist &key key)
  (rassoc-if (complement predicate) alist :key key))


(defun sublis (alist tree &key key test test-not)
  (let ((ass (assoc (funcall key tree) :test test :test-not test-not)))
    (if ass
        (cdr assoc)
        (typecase tree
          (cons
           (cons (sublis alist (car tree) :key key :test test :test-not test-not)
                 (sublis alist (cdr tree) :key key :test test :test-not test-not)))
          (t tree)))))

(defun nsublis (alist tree &key key test test-not)
  (sublvs alist tree :key key :test test :test-not test-not))