5
$\begingroup$

I need to build a sequence of n conditions separated by ||. Something like,

f = #1===f1[#2] || #1===f2[#2] || ... || #1===fn[#2] &

where the number n (integer, of course) is not fixed.

How can I do this?

I have tried with List and changing the Head but the trouble is that SameQ evaluates things too soon. The & at the end is apparently crucial.

$\endgroup$
5
$\begingroup$

Reference Replace, Apply:

fList = {f1, f2, f3, f4, f5};

Or @@@ Replace[Evaluate[fList] &, f_ :> # === f@#2, {2}]
#1 === f1[#2] || #1 === f2[#2] || #1 === f3[#2] || #1 === f4[#2] || #1 === f5[#2] &

Similar:

Replace[Function @@ {Or @@ fList}, f_ :> # === f@#2, {2}]

make[{x__}] := Replace[Or[x] &, f_ :> # === f@#2, {2}]
make[fList]

Modified approach

Inspired by WReach, if we may approach this flexibly we could simply write:

a === #[b] & /@ Or @@ fList

e.g.

1 === #[0] & /@ Or @@ {Sin, Cos, Tan}
True

Because Or is applied first this only evaluates functions until a match is found. I think this pattern is simple enough to use as-is, but we can of course package it if desired:

test[{fns__}][a_, b_] := a === #@b & /@ Or[fns]

test[{Sin, Cos, Tan}][1, 0]
True
| improve this answer | |
$\endgroup$
  • $\begingroup$ Thank you! Very useful $\endgroup$ – MaxB May 23 at 15:36
4
$\begingroup$

Some Hold[] trickery can be used for this:

fList = {f1, f2, f3, f4, f5};

Hold[Function][Or @@ Thread[Hold[SameQ][#1, Through[fList[#2]]]]] // ReleaseHold
   #1 === f1[#2] || #1 === f2[#2] || #1 === f3[#2] || #1 === f4[#2] || #1 === f5[#2] &
| improve this answer | |
$\endgroup$
4
$\begingroup$

If the application does not demand explicit use of code generation and Or then we might consider something like this:

test[fns___][x_, y_] := AnyTrue[{fns}, x === #[y] &]

This would allow us to define functions that test against any number of target functions. For example:

f = test[Sin, Cos, Tan];

or equivalently:

f = test @@ {Sin, Cos, Tan};

f could then be used like this:

f[0, Pi/2]
(* True *)

f[1, Pi/2]
(* True *)

f[ComplexInfinity, Pi/2]
(* True *)

f[10, Pi/2]
(* False *)
| improve this answer | |
$\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.