2
$\begingroup$

I believe this is simple but I couldn't figure out why this doesn't work. Everything looks good to me.

DeleteCases[{{0, 0, 0, 0, 0, 0, x, 1, -1}, {0, 0, 0, 1, 0, 0, x, 
   1, -1}}, _?(#[[1 ;; 6]] == {0, 0, 0, 0, 0, 0}) &]
$\endgroup$
9
  • 2
    $\begingroup$ Because Head[(_?(#[[1 ;; 6]] == {0, 0, 0, 0, 0, 0}) &)] is Function not Pattern. Use this instead: x_ /; (x[[1 ;; 6]] == {0, 0, 0, 0, 0, 0}) $\endgroup$ – flinty Jun 13 at 17:02
  • 4
    $\begingroup$ Or this, which may be what you had in mind: _?(#[[1 ;; 6]] == {0, 0, 0, 0, 0, 0} &) $\endgroup$ – Michael E2 Jun 13 at 17:04
  • $\begingroup$ @flinty I checked the one below as to make it. Aren't they similar? mathematica.stackexchange.com/questions/197423/… $\endgroup$ – anhnha Jun 13 at 17:05
  • 3
    $\begingroup$ The precedence of ? and &. The code in the question is equivalent to ( _?(#[[1 ;; 6]] == {0, 0, 0, 0, 0, 0}) ) &. In general _? body & is equivalent to (_? body) &. You need _?(body &). $\endgroup$ – Michael E2 Jun 13 at 17:13
  • 2
    $\begingroup$ When you're not sure about the precedence, just click n times on the code, and the code piece will be selected outwards according to the precedence. $\endgroup$ – xzczd Jun 13 at 17:17
5
$\begingroup$

As mentioned in the comments, it's a matter of precedence. When you're not sure about the precedence, just click n times on the code, and the code piece will be selected outwards according to the precedence:

enter image description here

As shown in the GIF above, after clicking on & 3 times, _?(#[[1 ;; 6]] == {0, 0, 0, 0, 0, 0}) & is selected i.e. the whole _?(#[[1 ;; 6]] == {0, 0, 0, 0, 0, 0}) has been included in the Function, which is undesired.

Alternatively, you can check the FullForm. It's not that handy, but still a good choice if you're not yet familiar with the real meaning of _, ?, &, etc.

_?(#[[1 ;; 6]] == {0, 0, 0, 0, 0, 0} &) // FullForm
(*
PatternTest[Blank[],Function[Equal[Part[Slot[1],Span[1,6]],List[0,0,0,0,0,0]]]]
 *)

_?(#[[1 ;; 6]] == {0, 0, 0, 0, 0, 0}) & // FullForm
(*
Function[PatternTest[Blank[],Equal[Part[Slot[1],Span[1,6]],List[0,0,0,0,0,0]]]]
 *)
$\endgroup$
1
  • 2
    $\begingroup$ And for the more keyboard oriented folks, you can also use Ctrl+. in place of clicks for "precedence highlighting". $\endgroup$ – NonDairyNeutrino Jun 13 at 18:36

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