newLISP Fan Club

Forum => newLISP in the real world => Topic started by: Fritz on October 02, 2009, 03:47:40 AM

Title: Searching in nested list
Post by: Fritz on October 02, 2009, 03:47:40 AM
I have converted xml-document to a big list. It looks like:


<group>
  <group>
    <element>
  </group>
  <element>
</group>


List:


(("group" ("group" ("element" (("code" "1")))) ("element" (("code" "2")))))

How can I find an element inside the list?


(assoc '("code" "2") xml-list)

returns nil.
Title:
Post by: Jeff on October 02, 2009, 05:05:15 AM
Here is a tutorial on drilling down into xml content in newlisp:



http://www.artfulcode.net/articles/working-xml-newlisp/



Here is a tutorial on using find-all with xml (among others) in newlisp:



http://www.artfulcode.net/articles/using-newlisps-find-all/
Title:
Post by: Lutz on October 02, 2009, 05:29:16 AM
'assoc' and 'find-all' only search on the top level of the list. But the '("code" "2") part is deeply nested into the list.



Use 'ref', 'ref-all' in this case and to change imformation use 'set-ref' and 'set-ref-all'


> (ref '("code" "2") xml-list)
(0 2 1 0)

> (set-ref '("code" "2") xml-list '("code" "99"))
(("group" ("group" ("element" (("code" "1")))) ("element" (("code" "99")))))

> xml-list
(("group" ("group" ("element" (("code" "1")))) ("element" (("code" "99")))))
>


(0 2 1 0) is called and index vector. If you cut off indices from the right side you can retrieve the higher level elements of 'xml-list'


> (nth '(0 2 1 0) xml-list)
("code" "99")

> (nth '(0 2 1) xml-list)
(("code" "99"))

> (nth '(0 2) xml-list)
("element" (("code" "99")))


you can also use 'setf' on the returned reference of 'nth' to change 'xml-list':


> (setf (nth '(0 2 1 0) xml-list) '("code" "111"))
("code" "111")
> xml-list
(("group" ("group" ("element" (("code" "1")))) ("element" (("code" "111")))))
>


PS: here is a whole chapter about "Modifying and searching lists":



http://www.newlisp.org/downloads/CodePatterns.html#toc-6
Title:
Post by: Fritz on October 02, 2009, 05:36:22 AM
Thanx! "ref" was what is need!