2
$\begingroup$

I'd like my function to work only for arrays with all positive members, eg:

myf[arr_] := Reverse@arr /; AllTrue[arr, Positive];

So

myf[{1,2}]
Output: {2,1}

and

myf[{-1,2}]
Output: myf[{-1,2}]

Well, but:

ToString /@ myf[{-1, 2}]
Output: Reverse::normal: Nonatomic expression expected at position 1 in Reverse[{-1, 2}].
Reverse[{-1, 2}]

I’m not very good at handling errors in Mathematica, so how to make the function not run, before next calculations start?

$\endgroup$
3
  • $\begingroup$ so how to make the function not run, But this is what happened? The function was not called? The result of myf[{-1, 2}] is echoed back, since there was no function found that meets this signature. What exactly do you want Mathematica to do in this case? $\endgroup$
    – Nasser
    Commented Apr 28 at 6:23
  • $\begingroup$ @Nasser, well may be to break all the next calculations and print message? $\endgroup$
    – lesobrod
    Commented Apr 28 at 6:25
  • $\begingroup$ May be then you can use Abort? will this work for you? myf[arr_] := If[ Not[AllTrue[arr, Positive]], Abort[], Reverse@arr] and now when you do ToString /@ myf[{-1, 2}] it will Abort. $\endgroup$
    – Nasser
    Commented Apr 28 at 6:28

2 Answers 2

4
$\begingroup$
myf[x_?VectorQ] /; AllTrue[x, Positive] := Reverse[x]

myf[x_?VectorQ] /; AnyTrue[x, Negative] := "Contains negative value(s)"

myf[x_] := "Not a real-valued vector"

myf[{1, 2, 3}]

{3, 2, 1}

myf[{1, -2, 3}]

"Contains negative value(s)"

myf[{1, {2}, 3}]

"Not a real-valued vector"

myf[{1, 2, 3 + 2 I}]

"Not a real-valued vector"

myf[{1, 2, "a"}]

"Not a real-valued vector"

$\endgroup$
3
$\begingroup$

One strategy could be as follows:

Clear[myf]
myf[arr_?(Not@*ArrayQ) ] := "Not an array";
myf[arr_?(Nand @@ Positive@Flatten@# &)] := "Not all positive";
myf[arr_] := Reverse@arr

You can substitute Abort[] in the first two cases, if you wish to suspend all calculation after the error is detected. You can also use a Catch/Throw combination.


Test:

{
 myf[{{1, 2}, {3, 4}}]
 , myf[{{1, 2}, {-3, 4}}]
 , myf[{{1, 2}, {4}}]
 , myf[{1}]
 , myf[{-1, 2}]
 , myf[{1, 2}]
 }

{{{3, 4}, {1, 2}}, "Not all positive", "Not an array", {1}, "Not all positive", \ {2, 1}}

$\endgroup$

Your Answer

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

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