Re: Question about function construction

• To: mathgroup at smc.vnet.net
• Subject: [mg119491] Re: Question about function construction
• From: DrMajorBob <btreat1 at austin.rr.com>
• Date: Mon, 6 Jun 2011 06:24:41 -0400 (EDT)

```Clear[pairs, hashTable]
constructHashTable[] :=
Module[{p = {{"key1", "value1"}, {"key2", "value2"}, {"key3",
"value3"}, {"key4", "value4"}}},
hashTable[key_String] := ((hashTable[#[[1]]] = #[[2]]) & /@ p;
hashTable@key); p]
pairs = constructHashTable[];
hashTable@"key1"

"value1"

hashTable /@ pairs[[All, 1]]

{"value1", "value2", "value3", "value4"}

or simpler:

Clear[pairs, hashTable]
constructHashTable[
pairs_List] := (Clear@hashTable; (hashTable[#[[1]]] = #[[2]]) & /@
pairs);
pairs = {{"key1", "value1"}, {"key2", "value2"}, {"key3",
"value3"}, {"key4", "value4"}};
constructHashTable[pairs];
hashTable@"key1"

"value1"

hashTable /@ pairs[[All, 1]]

{"value1", "value2", "value3", "value4"}

or more flexible:

Clear[pairs, hashTable]
constructHashTable[
pairs_List] := ((hashTable[pairs][#[[1]]] = #[[2]]) & /@ pairs);
pairs = {{"key1", "value1"}, {"key2", "value2"}, {"key3",
"value3"}, {"key4", "value4"}};
constructHashTable[pairs];
hashTable[pairs]@"key1"

"value1"

hashTable[pairs] /@ pairs[[All, 1]]

{"value1", "value2", "value3", "value4"}

Bobby

On Sun, 05 Jun 2011 06:04:29 -0500, ZiYuan Lin <ziyuang at 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~
>

--
DrMajorBob at yahoo.com

```

• Prev by Date: Re: plotting contours on a sphere [CORRECTION]
• Next by Date: Re: Curve Tracking and fetching Locator coordinates
• Previous by thread: Re: Question about function construction
• Next by thread: plotting contours on a sphere