0
$\begingroup$

Suppose that I want to have a function that is evaluated only when a user-specific, predefined flag is given out of a list of possible flags. For example

Clear[flags];
flags = {fyes, fno};

Clear[testf];
testf[flag_:flags] := 
  If[flag === fyes, Print["yes"], Print["no"]];

I am aware that the above snippet is wrong but that's the closest that I could get. testf should be evaluated only if flag is either fyes or fno and stay unevaluated for any other argument. How is this possible to be achieved?

$\endgroup$
4
  • $\begingroup$ testf[flag_ /; MemberQ[flags, flag]] := If[flag === fyes, Print["yes"], Print["no"]]; $\endgroup$
    – Syed
    Jan 20, 2022 at 11:11
  • $\begingroup$ Additionally, I would say that a function should not be reliant on a global variable; so please elaborate a bit further, if you consider it worthwhile. $\endgroup$
    – Syed
    Jan 20, 2022 at 11:17
  • $\begingroup$ Hi, and thank you. Well that's the point of a flag, right? To be a global variable "known" to the whole notebook such that it allows for specific situations... $\endgroup$
    – hal
    Jan 20, 2022 at 11:19
  • $\begingroup$ try testf[flag_: Alternatives @@ flags] := ...? $\endgroup$
    – kglr
    Jan 20, 2022 at 18:00

0

Your Answer

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