Re: DownValues and Cases
- To: mathgroup at smc.vnet.net
- Subject: [mg70817] Re: [mg70759] DownValues and Cases
- From: Oyvind Tafjord <tafjord at wolfram.com>
- Date: Sat, 28 Oct 2006 05:22:03 -0400 (EDT)
- References: <200610260639.CAA19605@smc.vnet.net>
Bruce Colletti wrote:
> Re Mathematica 5.2 under WinXP.
>
> The results of the first two Cases statements leads me to anticipate {{1,3.5}, {2,5}, {_,0}} as the output of the third.
>
> The output of the fourth Cases statement confirms this expectation.
>
> Unfortunately, the output of the third statement is the empty list.
>
> Why so? I've reviewed a related mid-July MathGroup thread, but don't see the answer (if it's there at all).
>
> Thankx.
>
> Bruce
>
> --------------------------
>
> f at 1=3.5;
> f@2=5;
> f[_]:=0;
> h=DownValues@f
>
> Out[4]={HoldPattern[f[1]] :> 3.5, HoldPattern[f[2]] :> 5, HoldPattern[f[_]] :> 0}
>
> Cases[h,HoldPattern[f[x_]] -> x,Infinity]
> Out[5]={1,2,_}
>
> Cases[h,(_ :> y_) -> y,Infinity]
> Out[6]={3.5,5,0}
>
> Cases[h,(HoldPattern[f[x_]] :> y_) -> {x,y},Infinity]
> Out[7]={}
>
> Cases[{a :> 4,b :> 5, c :> 6},(x_ :> y_) -> {x,y}]
> Out[8]={{a,4},{b,5},{c,6}}
Here is how I would do it:
In[10]:= Cases[h,(HoldPattern[HoldPattern][HoldPattern[f][x_]]:>y_):>{x,y}]
Out[10]= {{1,3.5},{2,5},{_,0}}
or (if all those HoldPatterns are confusing):
In[11]:= Cases[h,(Verbatim[HoldPattern][Verbatim[f][x_]]:>y_):>{x,y}]
Out[11]= {{1,3.5},{2,5},{_,0}}
Since HoldPattern is a pattern element, in order to match it you need to wrap it in HoldPattern (or Verbatim). Now you have the problem that f[x_] evaluates to 0, but wrapping a HoldPattern (or Verbatim) around the f will avoid this problem.
Oyvind Tafjord
Wolfram Research
- References:
- DownValues and Cases
- From: Bruce Colletti <vze269bv@verizon.net>
- DownValues and Cases