How to implement a dictionary?

Started by HJH, October 17, 2005, 06:24:34 AM

Previous topic - Next topic

HJH

Hello



I have been reading the passage http://www.newlisp.org/DesignPatterns.html#text_processing">http://www.newlisp.org/DesignPatterns.h ... processing">http://www.newlisp.org/DesignPatterns.html#text_processing of the newlisp design patterns document. For me the paragraph about text processing is too terse and I do not really understand how to implement a dictionary.



For example I would like to implement the example given under  http://en.wikipedia.org/wiki/Associative_array#Lisp">http://en.wikipedia.org/wiki/Associative_array#Lisp.

(It shows how to use a dictionary/associative array in various languages. The example shown has  name as key and  phone number as value attribute).



How do I create a dictionary/associative array in newlisp?



How do I access the value of a certain key element?



How do I add a new entry?



How do I remove an entry?



How do I get a list of all keys?





If somebody already has some code snippets / comments explaining this issue that would be a great help. Thanks in advance.



--HJH

HJH

#1
Well in the mean time I found the answer in the manual



I can use the following three predicates:

http://www.newlisp.org/downloads/newlisp_manual.html#assoc">http://www.newlisp.org/downloads/newlis ... html#assoc">http://www.newlisp.org/downloads/newlisp_manual.html#assoc


replace-assoc
and
lookup.



So the only question remaining is how to remove an existing entry.



--HJH

Lutz

#2
To remove an element from a list:



a) if you know the contents of the element use the last syntax of 'replace' (see manual with examples)



b) If you you know the position, use 'pop' (see maniual with examples)



Using dictionaries:



;add a new entry value
(set (sym "xyz" 'MyDictionary) 123)
(set (sym "123qwerty" 'MyDictionary) 5.6789)

; retrieve a value
(eval (sym "xyz" 'MyDictionary)) => 123

; show the entries
(symbols 'MyDictionary) => (MyDictionary:123qwerty MyDictionary:xyz)

; save the dictionary
(save "mydictionary.lsp" 'MyDictionary)

; reload the dictionary
(load "mydictionary.lsp")

; delete an entry
(delete (sym "xyz" 'MyDictionary))


If the names of the keys conform to newLISP variable symbol conventions you can just do:

(set 'MyDictionary:xyz 123)

; and
MyDictionary:xyz => 123


When using normal words prepend some other character (i.e. underscore) so they don't get confused with global names of built-in primitives in newLISP.



Be careful with looking up newLISP stuff in conventional Lisp or Scheme literature. newLISP works quite different in many instances.



Lutz

HJH

#3
Lutz,



Thank you for your explanations which I could use readily. A dictionary is a separate context where  the symbols correspond to the keys of the dictionary which are bound to values. The way how to construct an access symbol was unfamiliar to me but now I understand how it works.



--HJH