I'm trying to turn Off an error in an expression.

myFunction[x_] = 1/x
myFunction2[x_] = Quiet[1/x]  (*1/x*)
myFunction[0]
myFunction2[0]

I do not want to use :=, I also do not want to Globally turn Off this error. I want it using = such that it looks like:

myFunction3[x_] = TurnedOffError[1/x]  (*TurnedOffError[1/x]*)
myFunction3[0]
  • It won't work on subexpressions, though: a=3;myfunction2[x_] = a + Unevaluated@Quiet[1/x] will evaluate a on assignment, but will not evaluate 1/x on calling the function, but instead give (when calling with argument 0) the result 3+Unevaluated[Quiet[1/0]] – celtschk Apr 26 '14 at 17:27
up vote 6 down vote accepted

This is not an attempt to answer the question exactly as posed, because generally speaking I don't consider it a good idea to subvert Mathematica's evaluation process (e.g. by reaching up the stack and rewriting definitions based on their RHS before they evaluate) just to satisfy arbitrary syntactical preferences.

A better way, if you just want to stop Quiet from evaluating when the definition is made and before the message is actually going to be produced, is to Block it:

Block[{Quiet}, myFunction3[x_] = Quiet[1/x, Power::infy]] (* -> 1/x *)

myFunction3[0] (* -> ComplexInfinity [with no messages] *)

Something that works more similarly to what is described in the question, and still without requiring any awful hacks, is the following:

TurnedOffError /: HoldPattern[
  lhs_ = TurnedOffError[rhs_, msg : _MessageName | {___MessageName} | PatternSequence[]]
 ] := lhs = Unevaluated@Quiet[rhs, msg];

myFunction3[x_] = TurnedOffError[1/x, Power::infy] (* -> 1/x *)

myFunction3[0] (* -> ComplexInfinity [with no messages] *)

But this, of course, only works when TurnedOffError appears directly at level 1 inside Set.

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.