1 | ;;; replace.lisp |
---|
2 | ;;; |
---|
3 | ;;; Copyright (C) 2003 Peter Graves |
---|
4 | ;;; $Id: replace.lisp,v 1.3 2003-08-25 18:22:58 piso Exp $ |
---|
5 | ;;; |
---|
6 | ;;; This program is free software; you can redistribute it and/or |
---|
7 | ;;; modify it under the terms of the GNU General Public License |
---|
8 | ;;; as published by the Free Software Foundation; either version 2 |
---|
9 | ;;; of the License, or (at your option) any later version. |
---|
10 | ;;; |
---|
11 | ;;; This program is distributed in the hope that it will be useful, |
---|
12 | ;;; but WITHOUT ANY WARRANTY; without even the implied warranty of |
---|
13 | ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
---|
14 | ;;; GNU General Public License for more details. |
---|
15 | ;;; |
---|
16 | ;;; You should have received a copy of the GNU General Public License |
---|
17 | ;;; along with this program; if not, write to the Free Software |
---|
18 | ;;; Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. |
---|
19 | |
---|
20 | (in-package "COMMON-LISP") |
---|
21 | |
---|
22 | (export 'replace) |
---|
23 | |
---|
24 | ;;; REPLACE (from ECL) |
---|
25 | |
---|
26 | (defun bad-seq-limit (x &optional y) |
---|
27 | (error "bad sequence limit ~a" (if y (list x y) x))) |
---|
28 | |
---|
29 | (defun the-end (x y) |
---|
30 | (cond ((sys::fixnump x) |
---|
31 | (unless (<= x (length y)) |
---|
32 | (bad-seq-limit x)) |
---|
33 | x) |
---|
34 | ((null x) |
---|
35 | (length y)) |
---|
36 | (t (bad-seq-limit x)))) |
---|
37 | |
---|
38 | (defun the-start (x) |
---|
39 | (cond ((sys::fixnump x) |
---|
40 | (unless (>= x 0) |
---|
41 | (bad-seq-limit x)) |
---|
42 | x) |
---|
43 | ((null x) 0) |
---|
44 | (t (bad-seq-limit x)))) |
---|
45 | |
---|
46 | (defmacro with-start-end (start end seq &body body) |
---|
47 | `(let* ((,start (if ,start (the-start ,start) 0)) |
---|
48 | (,end (the-end ,end ,seq))) |
---|
49 | (unless (<= ,start ,end) (bad-seq-limit ,start ,end)) |
---|
50 | ,@ body)) |
---|
51 | |
---|
52 | (defun replace (sequence1 sequence2 |
---|
53 | &key start1 end1 |
---|
54 | start2 end2 ) |
---|
55 | (with-start-end start1 end1 sequence1 |
---|
56 | (with-start-end start2 end2 sequence2 |
---|
57 | (if (and (eq sequence1 sequence2) |
---|
58 | (> start1 start2)) |
---|
59 | (do* ((i 0 (1+ i)) |
---|
60 | (l (if (< (- end1 start1) |
---|
61 | (- end2 start2)) |
---|
62 | (- end1 start1) |
---|
63 | (- end2 start2))) |
---|
64 | (s1 (+ start1 (1- l)) (1- s1)) |
---|
65 | (s2 (+ start2 (1- l)) (1- s2))) |
---|
66 | ((>= i l) sequence1) |
---|
67 | (setf (elt sequence1 s1) (elt sequence2 s2))) |
---|
68 | (do ((i 0 (1+ i)) |
---|
69 | (l (if (< (- end1 start1) |
---|
70 | (- end2 start2)) |
---|
71 | (- end1 start1) |
---|
72 | (- end2 start2))) |
---|
73 | (s1 start1 (1+ s1)) |
---|
74 | (s2 start2 (1+ s2))) |
---|
75 | ((>= i l) sequence1) |
---|
76 | (setf (elt sequence1 s1) (elt sequence2 s2))))))) |
---|