# Which condition?

I want to substitute integers in a list with theirs square, I tried these

Cases[{{1, 2, 3}, a, {4, 5}}, t__ /; Element[t, Integers] :> t^2]
(*{{1, 4, 9}, {16, 25}}*)
Cases[{{1, 2, 3}, a, {4, 5}}, t__ /; IntegerQ[t] :> t^2]
(*{}*)


Why the first code works and the second doesn't? What is the difference between Element and IntegerQ?

• Consider using Cases[{{1, 2, 3}, s, {4, 5}}, t : {__Integer} :> t^2] instead. Apr 1, 2017 at 18:20
• Or Cases[{{1, 2, 3}, s, {4, 5}}, t : {__Integer}]^2. Or {{1, 2, 3}, a, {4, 5}} /. t_Integer :> t^2 (or t_?IntegerQ to be safer), if "substitute" is interpreted strictly. You might also be interested in PatternSequence, although I don't think it's the thing to use here. Apr 1, 2017 at 19:07

basically if you deconstruct you will see that Element in your case operates on the sublist level

{1, 2, 3} ∈ Integers
(* True *)

a ∈ Integers (* does not result in a boolean *)

{4,5} ∈ Integers
(* True *)


in second case your integers are present at level 2 and therefore you need to define the appropriate level in Cases

Cases[{{1, 2, 3}, a, {4, 5}}, t__ /; IntegerQ[t] :> t^2, {2}]
(* {1,4,9,16,25} *)


Note: this will not give the same form as Cases with Elements because you are matching objects at a different level

If you need a similar result with your second case, consider using this:

Cases[{{1, 2, 3}, a, {4, 5}}, pat : {__Integer} :> pat^2]
(* {{1, 4, 9}, {16, 25}} *)


with the named pattern pat your pattern matches at the same level as your Elements case

• @Mr.Wizard thanks for cleaning it up. always wondered how do you replace [Element] by its symbolic form Apr 1, 2017 at 19:21
• Both parts of my edit were made using halirutan's excellent editor extension; see: mathematica.meta.stackexchange.com/a/1044/121 Apr 1, 2017 at 19:30