Searching in nested list

Q&A's, tips, howto's
Locked
Fritz
Posts: 66
Joined: Sun Sep 27, 2009 12:08 am
Location: Russia

Searching in nested list

Post 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.

Jeff
Posts: 604
Joined: Sat Apr 07, 2007 2:23 pm
Location: Ohio
Contact:

Post 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/
Jeff
=====
Old programmers don't die. They just parse on...

Artful code

Lutz
Posts: 5289
Joined: Thu Sep 26, 2002 4:45 pm
Location: Pasadena, California
Contact:

Post 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

Fritz
Posts: 66
Joined: Sun Sep 27, 2009 12:08 am
Location: Russia

Post by Fritz »

Thanx! "ref" was what is need!

Locked