Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.soft-sys.math.mathematica > #2972 > unrolled thread
| Started by | Leonid Shifrin <lshifr@gmail.com> |
|---|---|
| First post | 2011-06-06 10:24 +0000 |
| Last post | 2011-06-06 10:24 +0000 |
| Articles | 1 — 1 participant |
Back to article view | Back to comp.soft-sys.math.mathematica
Re: Question about function construction Leonid Shifrin <lshifr@gmail.com> - 2011-06-06 10:24 +0000
| From | Leonid Shifrin <lshifr@gmail.com> |
|---|---|
| Date | 2011-06-06 10:24 +0000 |
| Subject | Re: Question about function construction |
| Message-ID | <isi9sb$m01$1@smc.vnet.net> |
What you effectively coded is that for every unknown key, the full hash
table is re-created. You Map the assignment (Set) on a list of keys, and
get a list of assigned values. The second time, you already have a specific
definition for that key, so that one fires, and you get a single value. Here
is what you should have done, in your approach:
ConstructHashtable[] :=
Module[{pairs = {{"key1", "value1"}, {"key2", "value2"}, {"key3",
"value3"}, {"key4", "value4"}}},
Clear[Hashtable];
(Hashtable[#[[1]]] = #[[2]]) & /@ pairs;]
although it would seem more natural to me to make the original keys and
values arguments for your constructor, as well as the hash table name.
Regards,
Leonid
On Sun, Jun 5, 2011 at 4:04 AM, ZiYuan Lin <ziyuang@gmail.com> wrote:
> Hi, there.
> I want to construct a function serving as a hash table. This is how I make
> it:
>
> ConstructHashtable[] :=
> Module[{pairs = {{"key1", "value1"}, {"key2", "value2"}, {"key3",
> "value3"}, {"key4", "value4"}}}, Clear[Hashtable];
> Hashtable[key_?StringQ] := (Hashtable[#[[1]]] = #[[2]]) & /@ pairs;]
>
> And then I run the code above together with a test:
>
> ConstructHashtable[]; Hashtable["key1"]
>
> Yet it returns all values:
>
> {"value1", "value2", "value3", "value4"}
>
> But if I run it again:
>
> Hashtable["key1"]
>
> It will get normal:
>
> "value1"
>
> What is the reason for this? Thank you~
>
>
Back to top | Article view | comp.soft-sys.math.mathematica
csiph-web