Page 1 of 1

Searching in nested list

Posted: Fri Oct 02, 2009 10:47 am
by Fritz
I have converted xml-document to a big list. It looks like:

Code: Select all

<group>
  <group>
    <element>
  </group>
  <element>
</group>
List:

Code: Select all

(("group" ("group" ("element" (("code" "1")))) ("element" (("code" "2")))))
How can I find an element inside the list?

Code: Select all

(assoc '("code" "2") xml-list)
returns nil.

Posted: Fri Oct 02, 2009 12:05 pm
by Jeff
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/usin ... -find-all/

Posted: Fri Oct 02, 2009 12:29 pm
by Lutz
'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'

Code: Select 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'

Code: Select all

> (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':

Code: Select all

> (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/CodePa ... html#toc-6

Posted: Fri Oct 02, 2009 12:36 pm
by Fritz
Thanx! "ref" was what is need!