I understand that the last call (f[1]
) returns True
because arg
does not exist and thus SameQ
tests a single argument ("ArgValue"
) which always returns True
. Therefore no comparison can be done here at all. Now it is not possible to use ValueQ
either, as arg
does not exist, and thus it has no value so ValueQ[arg]
would evaluate to ValueQ[]
. How to test whether arg
exists or not? I am aware that I can define another signature for just one argument (f[first_] := ...
), but I want to solve it inside the function, if it is possible.
ClearAll[f];
f[first_, arg___] := (arg === "ArgValue");
{f[1, "ArgValue"], f[1, "NonArgValue"], f[1]}
{True, False, True}
UPDATE
In general, I want to test whether any optional argument was passed to f
. Since f
is in reality a quite large function with a lot of optional arguments and occasionally called with a quite complex argument structure, I decided that I do not want to create complex patterns for each case (i.e. a different signature). Insted I check inside f
whether any extra argument was passed or not - which in tha baseline case means that there should be no extra argument. Thus f
shouldn't return False
in reality for only one argument (i.e. it still should perform some computation on its single argument), this is only for testing purposes here. A more realistic function would look like this:
ClearAll[func];
func[first_, arg___?overcomplicatedArgumentStructureQ] := Module[{...},
(* heavy computation *)
If[argExistQ[arg], (* do this *), (* do that *)];
(* some more heavy computation *)
];
{} =!= {arg}
is correct. You are testing the argument on the LHS already, using a test function. Leonid's{arg} === {"ArgValue"}
doesn't make sense in this case, and it also assumes a specific value for the optional argument. $\endgroup$arg
given tof
, it evaluates toFalse
, else it also checks whether the given argument equals a certain value. While your solution works as well, I still prefer Leonid's way, as it does the test on the rhs and does not touch the lhs of the function definition (which I implicitly wanted). $\endgroup${}
and{arg}
as a general suggestion as well, in my answer. $\endgroup$