How can I get the part of a list in front of a special element?

家住魔仙堡 提交于 2019-12-11 03:25:54

问题


With the MEMBER I get the searched element and the rest of the LIST. But how did I get the elements befor the searched element is coming?

(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) 


回答1:


Sometimes these functions are so easy to write and the solution is so transparent to read that there's no point in working out which combination of standard functions will do what you want:

(defun elts-before (l elt &key (test #'eql))
  (loop for e in l
        until (funcall test e elt)
        collect e))



回答2:


The accepted answer is correct (and more efficient), but if you are after standard functions, use LDIFF (i.e. list difference):

(let ((list '(ZEIT MAL LAENGE DURCH MASSE MAL ZEIT)))
    (ldiff list (MEMBER 'DURCH list)))

=> (ZEIT MAL LAENGE)



回答3:


You can return both parts with a single traversal:

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)


来源:https://stackoverflow.com/questions/58078153/how-can-i-get-the-part-of-a-list-in-front-of-a-special-element

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!