Skip to main content
Made title more descriptive of actual question. Minor clean-up
Source Link
m_goldberg
  • 108.1k
  • 16
  • 104
  • 259

How does patterns work in Which function definitions, when they overlapdefinition is used to evaluate an expression that matches the lefthand side of more than one definition?

In a case like this:

f[a_] :=a;= a;
f[{a_, b_}] :=a;= a;

I'm wondering whether I should expect f[{2, 3}] to return {2,3} or 2, because:

MatchQ[{2, 3}, a_] == MatchQ[{2, 3}, {a_, b_}]

Is the behaviour in this situation defined, or should I avoid this at all costs?

How does patterns work in function definitions, when they overlap

In a case like this:

f[a_]:=a;
f[{a_,b_}]:=a;

I'm wondering whether I should expect f[{2, 3}] to return {2,3} or 2, because:

MatchQ[{2, 3}, a_] == MatchQ[{2, 3}, {a_, b_}]

Is the behaviour in this situation defined, or should I avoid this at all costs?

Which function definition is used to evaluate an expression that matches the lefthand side of more than one definition?

In a case like this:

f[a_] := a;
f[{a_, b_}] := a;

I'm wondering whether I should expect f[{2, 3}] to return {2,3} or 2, because:

MatchQ[{2, 3}, a_] == MatchQ[{2, 3}, {a_, b_}]

Is the behaviour in this situation defined, or should I avoid this at all costs?

Source Link
Coolwater
  • 20.5k
  • 3
  • 39
  • 66

How does patterns work in function definitions, when they overlap

In a case like this:

f[a_]:=a;
f[{a_,b_}]:=a;

I'm wondering whether I should expect f[{2, 3}] to return {2,3} or 2, because:

MatchQ[{2, 3}, a_] == MatchQ[{2, 3}, {a_, b_}]

Is the behaviour in this situation defined, or should I avoid this at all costs?