Page 1 of 1

How to implement a dictionary?

Posted: Mon Oct 17, 2005 1:24 pm
by HJH
Hello

I have been reading the passage http://www.newlisp.org/DesignPatterns.h ... 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.
(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

Posted: Mon Oct 17, 2005 1:44 pm
by HJH
Well in the mean time I found the answer in the manual

I can use the following three predicates:
http://www.newlisp.org/downloads/newlis ... html#assoc

Code: Select all

replace-assoc
and

Code: Select all

lookup
.

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

--HJH

Posted: Mon Oct 17, 2005 2:13 pm
by Lutz
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:

Code: Select all

;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:

Code: Select all

(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

Posted: Tue Oct 18, 2005 7:35 pm
by HJH
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