0

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.

fpghost
  • 2,125
  • 2
  • 21
  • 25

2 Answers2

3

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:

Mathematica graphics

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

Mathematica graphics

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

Mathematica graphics

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

Mathematica graphics

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]
]

Mathematica graphics

See these questions for further guidance on testing arguments:

Placement of Condition /; expressions

Using a PatternTest versus a Condition for pattern matching

Mr.Wizard
  • 271,378
  • 34
  • 587
  • 1,371
1

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.

m_goldberg
  • 107,779
  • 16
  • 103
  • 257