# return {} when the function is given {}

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?

• Can you post your code, please? Or otherwise describe what you mean by something being wrong with the argument? Thanks. – Manuel --Moe-- G Oct 29 '19 at 18:55
• f[x_List] := If[Length[x] == 0, {}, func] – Bob Hanlon Oct 29 '19 at 21:06

## 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:

• It is the fist time I see _func := ..., don't act like it isn't awesome! – Kuba Oct 30 '19 at 8:19
• @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 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.

• 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
• Why not just define foo[{}]={}? – John Doty Oct 29 '19 at 20:19
• @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