Update lib.lisp to be more imperative and include a threading macro

Instead of (f (g (h (j (k x))))) we can write
(-> (k x)
    (j it)
    (h it)
    (g it)
    (f it))

which is works really well for particularly large and complicated
expressions.
This commit is contained in:
2024-10-30 15:15:04 +00:00
parent cd94c350e6
commit 07a5f754da

View File

@@ -10,16 +10,23 @@
"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)))
(if pos (if pos
(cons (subseq lst 0 pos) (list (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)
(if (or (null lst) (not (cdr lst))) (cond
(cons (list (car lst)) nil) ((or (null lst) (not (cdr lst)))
(if (member delim lst) (list (car lst)))
(destructuring-bind (first rest) (split-by-first lst delim) ((not (member delim lst))
(cons first (split-by-completely rest delim))) (list lst))
(list lst)))) (t
(loop
for (start rest) = (split-by-first lst delim)
then (split-by-first rest delim)
collect start
if (not (member delim rest))
collect rest
and do (loop-finish)))))
(defun get-lines (input-string) (defun get-lines (input-string)
(with-input-from-string (s input-string) (with-input-from-string (s input-string)
@@ -27,12 +34,15 @@
while line while line
collect line))) collect line)))
(defun id (x) x)
(defun remove-nth (n lst) (defun remove-nth (n lst)
(if (or (null lst) (= n 0)) (loop for el in lst
(cdr lst) for i from 0
(cons (car lst) if (not (= i n))
(remove-nth collect el))
(- n 1)
(cdr lst))))) (defmacro --> (first &rest functions)
(let ((builder first))
(loop for function in functions
do (setq builder `(let ((it ,builder))
,function)))
builder))