I have a function taking an array as argument and giving an output. However, sometimes my argument is {} (the empty array), then how can I get an output {} when my argument is {}? Actually, I want the output to be {} if there is anything wrong with the argument. How can I do this?
2 Answers
Actually, I want the output to be {} if there is anything wrong with the argument.
For this I recommend one or more definitions with patterns that only match a valid argument, and a fall-through definition for anything else. For example if the argument should be a nonempty list of integers:
(* primary definition *)
func[arg : {__Integer}] := Mean[arg]
(* fall-through definition *)
_func := {}
test:
func[{1, 2, 3}]
func[{1.23}]
func[{}]
func[1, 2, 3]
2 {} {} {}
Additional reading:
-
2$\begingroup$ It is the fist time I see
_func := ...
, don't act like it isn't awesome! $\endgroup$– Kuba ♦Oct 30, 2019 at 8:19 -
$\begingroup$ @Kuba Thank you, but I suspect you've seen it before and have forgotten. Likewise I seem to have forgotten who I learned it from. Nevertheless it's good I guess that this answer can remind people of this useful pattern construct. :-) $\endgroup$ Oct 31, 2019 at 3:27
One way is to make some definitions
foo[arr_] := {}
foo[{}] := {}
foo[arr_List] := "ok"
Mathematica will automatically pick the correct definition to use.
-
$\begingroup$ I define my function as foo[points : {{?NumericQ, _?NumericQ} ..}]. It is an array like this {{1,2},{3,4},{5,6},...}. Then when I define foo[arr]:={}, my function foo produces null only. $\endgroup$– lolOct 29, 2019 at 19:11
-
1
-
$\begingroup$ @JohnDoty yes, thanks, that is shorter. I guess I was trying to be explicit. But will update to use the shorter syntax. $\endgroup$– NasserOct 29, 2019 at 21:09
-
$\begingroup$ @lol Please update answer with MWE then. btw, you need to add '_' after the symbol name. So instead of
foo[arr]:={}
it should befoo[arr_]:={}
may be that is why it did not work for you. $\endgroup$– NasserOct 29, 2019 at 21:12
f[x_List] := If[Length[x] == 0, {}, func]
$\endgroup$