Introduce tests for split-by-first and split-by-completely

Allows one to split by string delimiter, or anything else.
This commit is contained in:
2024-10-30 22:33:31 +00:00
parent de4c5bbd53
commit 65b65a2a3e

View File

@@ -6,25 +6,25 @@
(string clist) (string clist)
(coerce clist 'string))) (coerce clist 'string)))
(defun split-by-first (lst delim) (defun split-by-first (lst delim &optional (test #'eq))
"Splits LST by the first instance of DELIM" "Splits LST by the first instance of DELIM"
(let ((pos (position delim lst))) (let ((pos (position delim lst :test test)))
(if pos (if pos
(list (subseq lst 0 pos) (subseq lst (+ pos 1))) (list (subseq lst 0 pos) (subseq lst (+ pos 1)))
(error (format nil "No instance of ~a was found in ~a" delim lst))))) (error (format nil "No instance of ~a was found in ~a" delim lst)))))
(defun split-by-completely (lst delim) (defun split-by-completely (lst delim &optional (test #'eq))
(cond (cond
((or (null lst) (not (cdr lst))) ((or (null lst) (not (cdr lst)))
(list (car lst))) (list (car lst)))
((not (member delim lst)) ((not (member delim lst :test test))
(list lst)) (list lst))
(t (t
(loop (loop
for (start rest) = (split-by-first lst delim) for (start rest) = (split-by-first lst delim test)
then (split-by-first rest delim) then (split-by-first rest delim test)
collect start collect start
if (not (member delim rest)) if (not (member delim rest :test test))
collect rest collect rest
and do (loop-finish))))) and do (loop-finish)))))