Hashes

Q&A's, tips, howto's
Locked
shercipher
Posts: 15
Joined: Sun May 10, 2009 3:11 am

Hashes

Post by shercipher »

Why does this work?

Code: Select all

(new Tree 'hash)
(hash "x" 0)
(hash "y" 1)
(hash "z" 2)

(hash "x")
0
But this not work?

Code: Select all

(dotree (x hash)
 (print x " " (hash x) " "))

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

Post by Lutz »

Two things;

1) in: (dotree (x hash) ...) x is a symbol not a string, you will get an error message when trying (hash x).

2) when doing: (hash "x" 0) the symbol created for "x" is _x with an underscore pre-pended.

http://www.newlisp.org/newlisp_manual.html#hash

(dotree (x hash) ...) produces the original symbols with the underscore prepended in the name. The same is true for (symbols hash).

To see the hash key like you entered them do a (hash) which will produce a list of hash key-value pairs. You can iterate through them with (dolist (h (hash)) ... ) e.g.:

Code: Select all

(hash) => (("x" 0) ("y" 1) ("z" 2))

(dolist (h (hash))
    (println (h 0) " -> " (h 1))
)

x -> 0
y -> 1
z -> 2
To do it with 'dotree', you would do this:

Code: Select all

(dotree (x hash)
 (println x " -> " (eval x))) 

hash:_x -> 0
hash:_y -> 1
hash:_z -> 2
The reason that hashs prepend an underscore is, to make all hash keys usable symbols which cannot be confused with global built-in functions. This is important when saving (serializing) then reloading a hash:

Code: Select all

(save "hash.lsp" 'hash)

; in a later newLISP session

(load "hash.lsp")

(hash "x") => 0
When using 'bayes-train' symbols are created in the same form, with the underscore prepended. This way natural language dictionaries created using 'bayes-train' can be treated as hashes to get individual word statistics.

shercipher
Posts: 15
Joined: Sun May 10, 2009 3:11 am

Post by shercipher »

Okay so all I have to do is evaluate the symbol from dotree.

Locked