5
$\begingroup$

I can define conditions on individual arguments to a function:

f[a_List/;condition(a),b_List/;condition(b)]:=(...)

I am wondering if there is a way of declaring something like this:

f[a_List,b_List/;condition(a,b)]:=(...)

so for instance, I might want to be sure that a and b are of the same size or that {a,b} follows a certain pattern for example.

I know I can leave the condition cases inside the body of the function but I am wondering if there is any way of avoiding that.

$\endgroup$
1
  • $\begingroup$ Note that patt /; test is a shorthand for Condition[patt, test]. You are writing f[a_, Condition[b_, test[a,b]]], but there is no a in the pattern in the first argument of Condition in this case. Note also that function definitions in Mathematica are nothing but patterns, so it is harmless to put the entire left hand side in the first argument of Condition, then you will have access to all symbols in the second argument of Condition. This is what eldo does. $\endgroup$
    – C. E.
    Dec 23, 2015 at 5:08

1 Answer 1

8
$\begingroup$

f[a_List,b_List/;condition(a,b)]:=(...) is not possible

Instead write:

fun[a_List, b_List] /; Length@a == Length@b := 1
fun[a_List, b_List] := 2

fun[Range@3, Range@3]

1

fun[Range@3, Range@4]

2

Also possible:

fun[a_List, b_List] := 1 /; Length@a == Length@b
$\endgroup$

Your Answer

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

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