0
$\begingroup$

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?

$\endgroup$
2
  • $\begingroup$ Consider using Cases[{{1, 2, 3}, s, {4, 5}}, t : {__Integer} :> t^2] instead. $\endgroup$ Commented Apr 1, 2017 at 18:20
  • $\begingroup$ 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. $\endgroup$
    – Michael E2
    Commented Apr 1, 2017 at 19:07

1 Answer 1

4
$\begingroup$

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

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

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.