Please ignore ^^^ possible duplicate (raised by me). The solution doesn't cover my case.
I'm trying to implement a simple hash table according to this top answer at "Is there HashTable structure in Wolfram Mathematica?"
That is, (copied from linked post)
(* Set some values in your table.*)
table[a] = foo; table[b] = bar; table[c] = baz;
(* Test whether some keys are present. *)
{ValueQ[table[a]], ValueQ[table[d]]}
(* Out: {True, False} *)
(* Get a list of all keys and values, as delayed rules. *)
DownValues[table]
(* Out: {HoldPattern[table[a]] :> foo, HoldPattern[table[b]] :> bar, HoldPattern[table[c]] :> baz} *)
(* Remove a key from your table. *)
Unset[table[b]]; ValueQ[table[b]]
(* Out: False *)
Testing a key fails, however, when supplied from a variable, e.g.
table[a] = foo; table[b] = bar; table[c] = baz;
{ValueQ[table[a]], ValueQ[table[d]]}
(* Out: {True, False} *)
key = d; ValueQ[table[key]]
(* Out: True *)
ValueQ's documentation does state that it "returns True if any evaluation takes place".
How should I test keys held in variables?
EDIT
I voted to close this question having found a possible duplicate, but after trying both of @halirutan's solutions, I'm sad to report that neither work for my case. @halirutan's test cases involved numerics, while mine involves a symbol with a DownValue
. So, I am still in search of a solution. Currently I am trying to decipher @halirutan's solutions so I can figure out where things are going wrong.
Association
s? $\endgroup$Association
was introduced in version 10. I have version 9, so I'd still appreciate an answer for my case. $\endgroup$ValueQ
works with respect to evaluation order. If you doValueQ[Evaluate[key]]
do you get the correct result? You should read up onAttributes
specifically,HoldAll
. $\endgroup$HoldAll
attribute, and sure, it appears to work, but I didn't have any confidence that it was actually working, since there's only two outcomes—True or False—and maybe some other effect was making it show the "correct" value. Please do post it as an answer if with your knowledge of howValueQ
works,Evaluate
is a proper solution :-) $\endgroup$