Searching in nested list

Started by Fritz, October 02, 2009, 03:47:40 AM

Previous topic - Next topic

Fritz

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.

Jeff

#1
Here is a tutorial on drilling down into xml content in newlisp:



http://www.artfulcode.net/articles/working-xml-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/">http://www.artfulcode.net/articles/usin ... -find-all/">http://www.artfulcode.net/articles/using-newlisps-find-all/
Jeff

=====

Old programmers don\'t die. They just parse on...



http://artfulcode.net\">Artful code

Lutz

#2
'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">http://www.newlisp.org/downloads/CodePa ... html#toc-6">http://www.newlisp.org/downloads/CodePatterns.html#toc-6

Fritz

#3
Thanx! "ref" was what is need!