2
$\begingroup$

I see that we can do associative arrays in Mathematica using functions that have implicit pattern arguments, as in

debyeTemperature[ "Aluminum" ] = 433 ;
debyeTemperature[ "Americium" ] = 121 ;
debyeTemperature[ "Antimony" ] = 220 ;
debyeTemperature[ "Argon" ] = 92.0 ;

debyeTemperature[ "Americium" ]

My guess is that ChemicalData[] uses something like this internally.

Is there a syntax for bulk initialization of such a hash function with pairs of values, perhaps like a similar perl hash initialization:

my %debyeTemperature = ("Aluminum" => 433,
                        "Americium" => 121,
                        "Antimony" => 220,
                        "Argon" => 92.0, ) ;

print "$debyeTemperature{'Americium'}\n" ;
$\endgroup$

2 Answers 2

2
$\begingroup$

You could set up a list of rules for the data and use that directly, optionally making a function wrapper for it:

debyeRules = {"Aluminum" -> 433, "Americium" -> 121,
              "Antimony" -> 220, "Argon" -> 92.0, _ -> Missing["NotAvailable"]};
debyeTemperature[s_] := s /. debyeRules
Attributes[debyeTemperature] = {Listable};

debyeTemperature[{"Aluminum", "Americium", "Abc"}]
(* {433, 121, Missing["NotAvailable"]} *)

If you have a lot of data you can run Dispatch on the rules once for faster lookup.

$\endgroup$
4
$\begingroup$

I am adding this answer because the solution based on lists of rules / Dispatch, while being very fine, has a limitation that you can't easily add more rules to the Dispatch-ed set of rules efficiently at a later stage. So, it is best suited for cases where you know all your key-value pairs in advance.

It is not difficult to add a little more convenient syntax to the DownValues-based one, though. For example:

ClearAll[makeHash];
makeHash[s_Symbol]:=
    Module[{},            
        ClearAll[s];
        s/:(s=rhs:{__Rule}):=
            Scan[                    
                (s[First[#1]]=Last[#1])&,
                Append[rhs,_->Missing["NotAvailable"]]
            ];
    ]

which can now be used as

makeHash[debyeRules]

Now you have initialized your symbol as a hash, so that you can use e.g. such initialization:

debyeRules = {"Aluminum" -> 433, "Americium" -> 121, "Antimony" -> 220, "Argon" -> 92.0}

You can check that the relevant key-value pairs have been added to the DownValues of debyeRules.

You can also add other "methods" into makeHash, to be attached to the symbol in question - they could test if it is of your hash type, etc.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.