B. Pym
2024-09-12 09:12:38 UTC
Define iterative and recursive versions of a function that takes an
object x and a vector v, and returns a list of all the objects that
immediately precede x in v.
(defun precedes (object vector)object x and a vector v, and returns a list of all the objects that
immediately precede x in v.
(loop for x across vector
and i from 0
when (and (equal x object) (> i 0))
collect (elt vector (1-i))))
(1-i)
Don't you think that that should be:
(1- i)
or
(- i 1)
?
It's shorter when you use a Lispy language instead of CL.
Gauche Scheme
(use srfi-42) ; list-ec
(define (precedes obj vec)
(list-ec (: x (index i) vec)
(if (and (> i 0) (equal? x obj)))
(ref vec (- i 1))))
(precedes 5 #(5 0 4 5 8 9 5))
===>
(4 9)
Another way:
(define (precedes o v)
(let ((l (vector->list vec)))
(filter-map
(^(a b) (and (equal? o a) b))
(cdr l)
l)))