How would you go about implementing a function that caches not the result but the fact that it didn't match a pattern? So that it doesn't waste time recomputing a complex time-consuming pattern condition every time it needs to evaluate the expression.
f[i_] := Module[{res},
res /; (
res = i^2(* some time consuming calculation *);
Print[i];
res < 8)]
I'd like that if I run the following example I don't get two Print statements but only one.
f[20];f[20];
An ideal solution would provide a way to make the pattern matcher skip a particular definition if it previously found it didn't fit. However, I'm happy enough with a nice way to make MMA just "let the unevaluated expression be" without wasting time every time it reevaluates it only to find it returns unevaluated.
So far I'm thinking of
Module[{fMatch},
fMatch[_] := True;
f[i_] := Module[{res},
res /; fMatch[i] && (
res = i^2
(* some time consuming calculation *);
Print[i];
fMatch[i] = res < 8)]
]
which seems to work I guess. You have better ideas, or think that needing this kind of construction is a sign of bad programming?
Update. I'd love to dig into this, but I need to run now. Perhaps you already know how it works? – Szabolcs Jan 24 '12 at 11:30Updatein my work a few times when it was absolutely necessary, and I even answered some question about it on MathGroup, in one of the threads:http://groups.google.com/group/comp.soft-sys.math.mathematica/browse_thread/thread/a864bf7059938c55. I believe however that the case at hand is somewhat different, at least as considered up to now. – Leonid Shifrin Jan 24 '12 at 11:41