Extract[expr, Position[expr, patt], h]

• To: mathgroup at smc.vnet.net
• Subject: [mg114045] Extract[expr, Position[expr, patt], h]
• From: kj <no.email at please.post>
• Date: Mon, 22 Nov 2010 07:35:40 -0500 (EST)

```
I am surprised that Mathematica does not have the equivalent of

extractMatching[expr_, patt_] := Extract[expr, Position[expr, patt]]
extractMatching[expr_, patt_, h_] := Extract[expr, Position[expr, patt], h]

The first one extracts all the subexpressions in expr that match
the pattern patt (including possibly expr itself).  The second
wraps the extracted patterns with the head h before evaluation.

I find myself needing one or the other of these functions all the
time.  Is there a way to make them automatically available to all
my Mathematica sessions?

But maybe they already exist in Mathematica, and I just missed
them.  If so, please let me know.

Alternatively, maybe my reliance on extractMatching is diagnostic
of my having some thought habits that are counterproductive when
doing rules-based programming (analogous to the habit developed
through the practice of procedural programming of using for-loops
and while-loops)...

Just to be concrete, here's the latest task for which I needed this
functionality: Unset all the defined expressions foo[i] where i is
some positive integer.  The solution I found (after many, many
failed attempts!) turned out to be

extractMatching[DownValues[foo], HoldPattern[foo[x_ /; x > 0]], Unset]

(The HoldPattern was necessitated by the fact that some of the
DownValues of foo recursively refer to foo; without the HoldPattern
one gets an infinite recursion.)

Is there a simpler solution to this problem in terms Mathematica
built-in functions?

TIA!

~kj

```

• Prev by Date: Re: Mathematica 8
• Next by Date: Need help NIntegrating stepwise 3D probability density functions
• Previous by thread: Re: Question on FinancialDerivative in Ver 8
• Next by thread: Re: Extract[expr, Position[expr, patt], h]