8
$\begingroup$

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?

$\endgroup$
2
  • $\begingroup$ Can you post your code, please? Or otherwise describe what you mean by something being wrong with the argument? Thanks. $\endgroup$ Oct 29, 2019 at 18:55
  • $\begingroup$ f[x_List] := If[Length[x] == 0, {}, func] $\endgroup$
    – Bob Hanlon
    Oct 29, 2019 at 21:06

2 Answers 2

16
$\begingroup$

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:

$\endgroup$
2
  • 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$
    – Mr.Wizard
    Oct 31, 2019 at 3:27
4
$\begingroup$

One way is to make some definitions

foo[arr_] := {}
foo[{}] := {} 
foo[arr_List] := "ok"

Mathematica graphics

Mathematica will automatically pick the correct definition to use.

$\endgroup$
4
  • $\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$
    – lol
    Oct 29, 2019 at 19:11
  • 1
    $\begingroup$ Why not just define foo[{}]={}? $\endgroup$
    – John Doty
    Oct 29, 2019 at 20:19
  • $\begingroup$ @JohnDoty yes, thanks, that is shorter. I guess I was trying to be explicit. But will update to use the shorter syntax. $\endgroup$
    – Nasser
    Oct 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 be foo[arr_]:={} may be that is why it did not work for you. $\endgroup$
    – Nasser
    Oct 29, 2019 at 21:12

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.