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?
Asked
Active
Viewed 622 times
2 Answers
16
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:
Mr.Wizard
- 271,378
- 34
- 587
- 1,371
-
2
-
@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. :-) – Mr.Wizard Oct 31 '19 at 03:27
4
One way is to make some definitions
foo[arr_] := {}
foo[{}] := {}
foo[arr_List] := "ok"

Mathematica will automatically pick the correct definition to use.
Nasser
- 143,286
- 11
- 154
- 359
-
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. – lol Oct 29 '19 at 19:11
-
1
-
@JohnDoty yes, thanks, that is shorter. I guess I was trying to be explicit. But will update to use the shorter syntax. – Nasser Oct 29 '19 at 21:09
-
@lol Please update answer with MWE then. btw, you need to add '' after the symbol name. So instead of
foo[arr]:={}it should be `foo[arr]:={}` may be that is why it did not work for you. – Nasser Oct 29 '19 at 21:12
f[x_List] := If[Length[x] == 0, {}, func]– Bob Hanlon Oct 29 '19 at 21:06