使用MEMBER,我得到了被搜索的元素和LIST的其余部分。但是在搜索到的元素出现之前,我如何获得这些元素?
(CDR (MEMBER 'DURCH '(ZEIT MAL LAENGE DURCH MASSE MAL ZEIT))); with this I get (MASSE MAL ZEIT)
;But how did I get (ZEIT MAL LAENGE)
Run Code Online (Sandbox Code Playgroud)
有时,这些函数很容易编写,而解决方案却如此透明以至于无法确定标准函数的哪种组合可以满足您的需求:
(defun elts-before (l elt &key (test #'eql))
(loop for e in l
until (funcall test e elt)
collect e))
Run Code Online (Sandbox Code Playgroud)
可接受的答案是正确的(并且效率更高),但是如果您追求标准功能,请使用LDIFF(即,列表差异):
(let ((list '(ZEIT MAL LAENGE DURCH MASSE MAL ZEIT)))
(ldiff list (MEMBER 'DURCH list)))
=> (ZEIT MAL LAENGE)
Run Code Online (Sandbox Code Playgroud)
您可以一次遍历返回两个部分:
CL-USER> (defun split-at (item list &key (test #'eql))
(loop :for (x . rest) :on list
:until (funcall test x item)
:collect x :into head
:finally (return (values head rest))))
SPLIT-AT
CL-USER> (split-at 'durch '(a mal b durch c mal d))
(A MAL B)
(C MAL D)
Run Code Online (Sandbox Code Playgroud)