I am trying to write some codes to judge if each row of a matrix contains any negative numbers. For example mat = {{1, 2, 3}, {-1, 2, 3}, {0, 2, 3}}, and AnyTrue[mat[[1]], # < 0 &], AnyTrue[mat[[2]], # < 0 &], AnyTrue[mat[[3]], # < 0 &] will give False, True, False for each of the three rows. Then I prefer to have a shorthand for this, e.g., AnyTrue[#, ## < 0 &] & /@ mat will give {False, True, False}. The result seems to be correct, but is this shorthand with # and ## in the same statement legitimate? I recall to have seen in Mathematica documentation some time ago using # and ## to represent things of "different levels," but can anyone help me find where this is in the documentation?

  • 4
    $\begingroup$ If you are ever unsure what a symbol in Mathematica means, simply select it and press F1 (or Cmd + Shift + F on macOS) - it will open the help page of the associated symbol. In your case, you will get to Slot and SlotSequence, which as you can see there have different meanings than you assume $\endgroup$ – Lukas Lang Jan 16 at 22:32
  • 1
    $\begingroup$ You can use parentheses to restrict inner pure function: AnyTrue[#, (# < 0 &)] & /@ mat or simply use Negative as testing function: AnyTrue[#, Negative] & /@ mat $\endgroup$ – Alx Jan 16 at 23:16
  • $\begingroup$ # != 3 & /@ Total /@ UnitStep@mat $\endgroup$ – OkkesDulgerci Jan 16 at 23:57
  • $\begingroup$ After looking at the documentation, it's a good exercise to discover why your code worked by accident and post as a self-answer. $\endgroup$ – lirtosiast Jan 17 at 0:12
  • 3
    $\begingroup$ You can also use the operator forms: AnyTrue[ Negative] /@ mat or AnyTrue[ #<0&] /@ mat $\endgroup$ – kglr Jan 17 at 2:10

According to the documentation for Slot:

When pure functions are nested, the meaning of slots may become ambiguous, in which case parameters must be specified using an explicit Function construction with named parameters.

So, your nested functions here may or may not work as expected.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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