Hashes

Started by shercipher, May 21, 2009, 03:02:53 PM

Previous topic - Next topic

shercipher

Why does this work?



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

(hash "x")
0


But this not work?



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

Lutz

#1
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">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.:


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


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


(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

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