3
$\begingroup$

For example, suppose that foo is defined like this.

foo[x_Integer, y_Integer] := x + y;

Then, any expression with head foo that does not match the pattern given above will remain "unevaluated". E.g., foo[3] "evaluates" to foo[3].

Although I recognize that there are situations where one may want precisely this behavior, in most of my programming I don't. Quite the contrary: I want expressions like foo[3] to be treated as malformed, IOW, as errors, and therefore to result in a loud, unequivocal failure whenever they are evaluated.

Hence, I find myself writing a lot of code of the form

foo[x_Integer, y_Integer] := x + y;
foo[___] := Abort[];

(Actually, I use a slightly embellished version of Abort[].)

But including a line like

foo[___] := Abort[];

for every function one defines adds up to a lot of hard-to-maintain clutter-code.

Does Mathematica have some other way to achieve the same thing with less clutter?

$\endgroup$
9
  • $\begingroup$ Related question: mathematica.stackexchange.com/q/48208/3066 $\endgroup$
    – m_goldberg
    Commented Dec 10, 2016 at 17:37
  • 1
    $\begingroup$ Possible duplicate: mathematica.stackexchange.com/q/29321/12 $\endgroup$
    – Szabolcs
    Commented Dec 10, 2016 at 17:41
  • 1
    $\begingroup$ The practice of adding a definition of the form foo[___] := ... is pretty much the standard idiom. I have never found that it produced any code maintenance problems. $\endgroup$
    – m_goldberg
    Commented Dec 10, 2016 at 17:41
  • 1
    $\begingroup$ Abort is a rather drastic measure, and IMO not really the right solution for a reusable functions ... Unfortunately there's no one consistent way to deal with failures in Mathematica. Typical ways are: keep unevaluated and issue a message. Return $Failed, with or without a message. Return Failure[...]. In functions internal to your package: use Throw maybe. $\endgroup$
    – Szabolcs
    Commented Dec 10, 2016 at 17:42
  • 2
    $\begingroup$ The common practice is to make a call to Message and print an informative error message. $\endgroup$
    – m_goldberg
    Commented Dec 10, 2016 at 17:43

1 Answer 1

2
$\begingroup$

Instead of foo[___] := Abort[] try this

LHS_foo := RuleCondition[Developer`CheckArgumentCount[LHS, 2, 2]; Fail];

It uses lots of undocumented functions, so it might not be to your taste.

It accomplishes @m_goldberg 's suggestion in the comments.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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