# Creating an advance If statement nest with /; as conditions

Create a slightly more advanced version that does not use nested If statements, but instead uses the conditional /; to determine whether the function is evaluated at all. If the data are not ordered pairs, or the {min, max} are not in range, the function should just echo back what you initially typed into it.

This is what I have so far. I'm not sure what to modify:

function8[data : {{_, _} ..}, min_, max_] :=
Mean [data[[All, 2]] /; min <= #[[1]] <= max &];
function8[data : {{_, _} ..}, min_, max_] :=
InputForm["Not data within range!"] /; min >= #[[1]] >= max &;

If the data are not ordered pairs, or the {min, max} are not in range, the function should just echo back what you initially typed into it.

This requires that no definition match under the given condition. For example

foo[data : {{_, _} ..}, min_, max_] /; max >= min := "some action"

Now if any part of this pattern including the Condition does not match the input is returned:

foo[{{1, 2}, {3, 4}}, 5, 2]

foo[{1, 2, 3}, 3, 5]
foo[{{1, 2}, {3, 4}}, 5, 2]

foo[{1, 2, 3}, 3, 5]

A valid input evaluates:

foo[{{1, 2}, {3, 4}}, 3, 8]
"some action"

If your condition depends on the output of the function then you need a very specific use of Condition

lhs := Module[{vars}, rhs /; test] allows local variables to be shared between test and rhs. You can use the same construction with Block and With.

So maybe you want something like this:

Clear[foo]

foo[data : {{_, _} ..}, min_, max_] :=
Module[{mean},
mean = Mean[ data[[All, 2]] ];
mean /; min <= mean <= max
]

Now:

foo[{{1, 2}, {3, 4}}, 1, 5]
3

But:

foo[{{1, 2}, {3, 4}}, 5, 7]
foo[{{1, 2}, {3, 4}}, 5, 7]

And any other bad input is returned as-is:

foo["not good data", 5, 7]
foo["not good data", 5, 7]

• nice and simple +1 Feb 10, 2017 at 10:54

You only need to make one conditional definition, and leave the "error handling" to a default definition that will apply in those cases in which the condition fails to match:

ClearAll[function8]

(* Conditional definition; a "special case" *)
function8[data : {{_, _} ..}, min_, max_] /;
min <= Min[data[[All, 2]]] && max >= Max[data[[All, 2]]] :=
Mean[data[[All, 2]]]

(* Catch-all definition: all other cases *)
function8[data : {{_, _} ..}, min_, max_] := "No data within range!"

function8[{{1, -2}, {2, -1}, {3, 5}, {4, 10}}, -4, 15]
(* Out: 3 *)

function8[{{1, -2}, {2, -1}, {3, 5}, {4, 10}}, 40, 50]
(* Out: "No data within range!" *)
function8[data : {{_, _} ..}, min_,max_] := (Mean[data[[All, 2]]] /;
AnyTrue[{Min[data], Max[data]}, IntervalMemberQ[Interval[{min, max}], #] &])

function8[data : {{_, _} ..}, min_, max_] := "No data in range"