# Pattern constraint for two or more variables

Is it possible to have a pattern constraint for a function with two or more variables where the pattern is a relation between the vars being accepted e.g.

f[x_,y_]:=...


and I want say, x< 10y. I don't think something like

f[x_,y_/; x<10y]


will work, or other variants of this that I have tried.

-
...or f[x_, y_] /; x < 10 y := (* stuff *) – J. M. Nov 9 '12 at 12:28
Ah, I see thanks. – fpghost Nov 9 '12 at 12:58
Okay, go answer your own question if you understood what I was saying... – J. M. Nov 9 '12 at 13:20
– Mr.Wizard Nov 10 '12 at 8:20

Let's look at why your attempt failed.

f[x_, y_ /; x < 10 y] := Mod[x, y]


Although the FrontEnd syntax highlighter is sometimes wrong it is helpful in this case:

Notice that the x on the left-hand side is not colored as a pattern name. Indeed this is why it does not work as you desire. Observe the Trace:

f[5, 10] // Trace


You can see that this attempts comparision to a literal x rather than the value 5. This can be a useful behavior for global conditions, e.g.:

x = 70;

f[5, 10] // Trace


As to why this happens: the values of patterns are only substituted on the right-hand side of operators such as =, :=, :> and pivotally /;. Therefore we want both patterns x_ and y_ on the LHS of /; so that they will be substituted in its RHS.

ClearAll[f]

f[x_, y_] /; x < 10 y := Mod[x, y]

f[5, 10] // Trace


Here is the TreeForm of the definition in case the parsing is not apparent:

TreeForm @ Unevaluated @ Unevaluated[
f[x_, y_] /; x < 10 y := Mod[x, y]
]


See these questions for further guidance on testing arguments:

Placement of Condition /; expressions

Using a PatternTest versus a Condition for pattern matching

-

The following seems to work just fine:

f[x_, y_] := x y /; x < 10 y


Yes, this was said in a comment to the question, but I thought there should be a real answer easy for newcomers to find.

-
Filtering the pattern match on the left-hand side as in J.M.'s comment is actually more efficient, since the filter is applied earlier. – Chris Degnen Nov 10 '12 at 1:33
@ChrisDegnen Yep. In fact J.M.'s is twice as fast – Dr. belisarius Nov 10 '12 at 5:00