A number of functions provide for results to be wrapped in an arbitrary head. This is very important in cases where the results should not be evaluated. Take Level as an example:
expr = Hold[{2/2, g[8/4], 1/0}];
Level[expr, {-2}, Hold]
Hold[1/2, 1/4, 1/0]
Cases however provides no such parameter, causing undesired evaluation:
Cases[expr, _Times, 3]
Power::infy: Infinite expression 1/0 encountered. >>
{1, 2, ComplexInfinity} (* failure *)
How can this behavior be attained?
Cases[Unevaluated[expr], Replace[...],args]. – Leonid Shifrin Sep 06 '13 at 06:59Casessyntax.Unevaluated[expr]does make sense regarding the nameholdCasesbut it was my intent instead to implement this as if it was a parameter ofCases, just as it is forLevel, andCasesdoes not haveHoldFirst. – Mr.Wizard Sep 06 '13 at 07:02heldCases[expr_, rule_, args___, head_] := Join @@ Cases[expr, makeHeld @ rule, args] /. HoldComplete -> head– RunnyKine Sep 06 '13 at 07:59head @@ Join @@ Cases[. . .]. I almost did this but I realized it was no shorter to include it as an argument. (Well, I guess it's one character shorter, but even I don't make too much of that.) – Mr.Wizard Sep 06 '13 at 08:04Unevaluatedis that otherwise the expression will evaluate, once passed toheldCases, even when you wrap it in one level ofUnevaluated, because there is a rewrite stepheldCasestoCases. In other words, when I need to destructure an expression while keeping it unevaluated, I useCases[Unevaluated[expr],...], while doing the same withheldCasesasheldCases[Unevaluated[expr],...won't work with your current code. Re: rewrite - quite nice, I agree. – Leonid Shifrin Sep 06 '13 at 10:49x? Thanks. – rcollyer Sep 06 '13 at 12:56x := godObject["rcollyer", "confusticate"]-- meet me in chat ;-) – Mr.Wizard Sep 06 '13 at 12:59