9
$\begingroup$

New to mathematica and also not entirely sure how to phrase my questions but basically I have a function I'm trying to write where several inputs will return the same value. For example,

function[ax, ax] = output1
function[ax, ay] = output1
function[ax, az] = output1
...
function[az, az] = output1

Is there a way to write this along the lines of:

function[ax||ay||az, ax||ay||az] = output1

instead of having to list all the possibilities out?

I tried this and it didn't seem to work so I was wondering if I'm missing something.

$\endgroup$
12
$\begingroup$

You almost got it right. You can use the pattern Alternatives ( | ) to do what you ask.

f[a | b | c, a | b | c] = "inputs ok";

or more exotically

g[(a | b | c) ..] = "inputs ok";

which allows one or more repetitions.

Tests

f @@@ Tuples[{a, b, c}, 2]
{"inputs ok", "inputs ok", "inputs ok", "inputs ok", "inputs ok", "inputs ok", 
 "inputs ok", "inputs ok", "inputs ok"}
g @@@ Tuples[{a, b, c}, 3]
{"inputs ok", "inputs ok", "inputs ok", "inputs ok", "inputs ok", 
 "inputs ok", "inputs ok", "inputs ok", "inputs ok", "inputs ok", 
 "inputs ok", "inputs ok", "inputs ok", "inputs ok", "inputs ok", 
 "inputs ok", "inputs ok", "inputs ok", "inputs ok", "inputs ok", 
 "inputs ok", "inputs ok", "inputs ok", "inputs ok", "inputs ok", 
 "inputs ok", "inputs ok"}
$\endgroup$
1
$\begingroup$

If you already have lists of acceptable arguments, you might want to do it like this.

listX = {1, 2, 3, x};
listY = {1};

f[x_, y_] /;
  MemberQ[listX, x] && MemberQ[listY, y] := "good"

f[__] := "evil"

f @@@ {{1, 1}, {1, 2}, {2, 1}, {2, 2}, {x, 1}}

{"good", "evil", "good", "evil", "good"}

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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