3
$\begingroup$

Why do these 2 input return different output when considered at different level lev

Cases[{{1, 2, 3}, a, {4, 5^a, {a^6}}}, t:{__Integer} :> t, {lev}]  
Cases[{{1, 2, 3}, a, {4, 5^a, {a^6}}}, t__ /; Element[t,Integers] :> t, {lev}]  

(They give the same output only at level -2 and 1, eg

Do[
 Print[ lev, "\n",
  Cases[{{1, 2, 3}, a, {4, 5^a, {a^6}}}, t : {__Integer} :> t, {lev}],
   "\n",
  Cases[{{1, 2, 3}, a, {4, 5^a, {a^6}}}, 
   t__ /; Element[t, Integers] :> t, {lev}], "\n"],
 {lev, -3, 4}]

-3
{}
{}


-2
{{1,2,3}}
{{1,2,3}}


-1
{}
{1,2,3,4,5,6}


0
{}
{}


1
{{1,2,3}}
{{1,2,3}}


2
{}
{1,2,3,4}


3
{}
{5}


4
{}
{6}
$\endgroup$
  • $\begingroup$ Element can accept a single expression, as well as a list of expressions, for its first argument, so you need to include single-element pattern in your first code. i.e. you could do: Cases[{{1, 2, 3}, a, {4, 5^a, {a^6}}}, t : _Integer | {__Integer} :> t, {lev}] $\endgroup$ – JungHwan Min Nov 1 '16 at 6:55
3
$\begingroup$

Element can accept a single expression, as well as a list of expressions, for its first argument, so you need to include single-element pattern in your first code.

That is,

Cases[{{1, 2, 3}, a, {4, 5^a, {a^6}}}, t : _Integer | {__Integer} :> t, {lev}]

Verfication:

Do[Print[lev, "\n", 
  Cases[{{1, 2, 3}, a, {4, 5^a, {a^6}}}, 
   t : _Integer | {__Integer} :> t, {lev}], "\n", 
  Cases[{{1, 2, 3}, a, {4, 5^a, {a^6}}}, 
   t__ /; Element[t, Integers] :> t, {lev}], "\n"], {lev, -3, 4}]

-3
{}
{}


-2
{{1,2,3}}
{{1,2,3}}


-1
{1,2,3,4,5,6}
{1,2,3,4,5,6}


0
{}
{}


1
{{1,2,3}}
{{1,2,3}}


2
{1,2,3,4}
{1,2,3,4}


3
{5}
{5}


4
{6}
{6}
$\endgroup$

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.