3 ;; JSCL is free software: you can redistribute it and/or
4 ;; modify it under the terms of the GNU General Public License as
5 ;; published by the Free Software Foundation, either version 3 of the
6 ;; License, or (at your option) any later version.
8 ;; JSCL is distributed in the hope that it will be useful, but
9 ;; WITHOUT ANY WARRANTY; without even the implied warranty of
10 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 ;; General Public License for more details.
13 ;; You should have received a copy of the GNU General Public License
14 ;; along with JSCL. If not, see <http://www.gnu.org/licenses/>.
16 (defmacro do-sequence ((elt seq &optional (index (gensym "i") index-p)) &body body)
17 (let ((nseq (gensym "seq")))
19 (error "`~S' must be a symbol." elt))
29 (dotimes (,index (length ,nseq))
30 (let ((,elt (aref ,nseq ,index)))
33 (defun find (item seq &key key (test #'eql))
36 (when (funcall test (funcall key x) item)
39 (when (funcall test x item)
42 (defun find-if (predicate sequence &key key)
44 (do-sequence (x sequence)
45 (when (funcall predicate (funcall key x))
47 (do-sequence (x sequence)
48 (when (funcall predicate x)
51 (defun position (elt sequence &key (test #'eql))
52 (do-sequence (x seq index)
53 (when (funcall test elt x)
61 (let* ((head (cons nil nil))
63 (do-sequence (elt seq)
65 (let ((new (list elt)))
71 (do-sequence (elt seq index)
73 ;; Copy the beginning of the vector only when we find an element
74 ;; that does not match.
76 (setq vector (make-array 0))
78 (vector-push-extend (aref seq i) vector)))
80 (vector-push-extend elt vector))))
84 (defun some (function seq)
85 (do-sequence (elt seq)
86 (when (funcall function elt)
87 (return-from some t))))
89 (defun every (function seq)
90 (do-sequence (elt seq)
91 (unless (funcall function elt)
92 (return-from every nil)))
95 (defun remove-if (func seq)
97 ((listp seq) (list-remove-if func seq nil))
98 ((arrayp seq) (vector-remove-if func seq nil))
99 (t (error "`~S' is not of type SEQUENCE" seq))))
101 (defun remove-if-not (func seq)
103 ((listp seq) (list-remove-if func seq t))
104 ((arrayp seq) (vector-remove-if func seq t))
105 (t (error "`~S' is not of type SEQUENCE" seq))))
107 (defun list-remove-if (func list negate)
110 (let ((test (funcall func (car list))))
111 (if (if negate (not test) test)
112 (list-remove-if func (cdr list) negate)
113 (cons (car list) (list-remove-if func (cdr list) negate))))))
115 (defun vector-remove-if (func vector negate)
116 (let ((out-vector (make-array 0)))
117 (do-sequence (element vector i)
118 (let ((test (funcall func element)))
119 (when (if negate test (not test))
120 (vector-push-extend element out-vector))))
123 ;;; TODO: Support both List and vectors in the following functions
125 (defun subseq (seq a &optional b)