Services & Resources / Wolfram Forums / MathGroup Archive

MathGroup Archive 2008

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: Matching HoldPattern explicitly

  • To: mathgroup at
  • Subject: [mg85800] Re: Matching HoldPattern explicitly
  • From: Albert Retey <awnl at>
  • Date: Fri, 22 Feb 2008 07:26:09 -0500 (EST)
  • References: <fpm6i0$2kc$>


> I'm trying to use Mathematica symbols as dictionaries. In particular
> if I have (kk[1, 2] = 3; kk[3, 4] = 4;), I'd like a function "keys"
> that would accept kk, and return {{1,2},{3,4}}.
> A recipie on
> suggests to do
> keys[dict_] := Map[#[[1]] /. {HoldPattern[dict[x_]] -> x} &,
> DownValues[dict]]
> However, this doesn't quite work (p:HoldPattern[x] doesn't match
> "HoldPattern[x]"). Verbatim[HoldPattern[dict... doesn't work because I
> need to do a substitution for local dict variable. So my question is
> 1. What's the best way to match HoldPattern explicitly, while allowing
> for local variable substitutions inside "HoldPattern" pattern

This gives the keys for the above case:


Note that Verbatim is wrapped around HoldPattern only and that you need 
two _ in the pattern x__, otherwise you can not find your keys because 
they are sequences.

> 2. What is the best way of implementing Python like dictionaries in
> Mathematica?

I would not consider these really "Python like" but for most practical
purposes using the downvalues of symbols works quite well. One of the
differences is that Mathematica-Sequences and Pyhton tuples are not
exactly the same, as you have seen in the above.

Other than that, a list of rules comes to mind as an alternative data 
structure to store key-value pairs in mathematica:

kk = {{1,2}->3,{3,4}->4}

of course accessing the values looks very different and which approach 
is more suitable depends a lot on what you try to achieve...



  • Prev by Date: Re: squared norm in Mathematica
  • Next by Date: Re: IMS IMTEK mailing list
  • Previous by thread: Matching HoldPattern explicitly
  • Next by thread: IMS IMTEK mailing list