# Replacements: using condition to restrict to parts that satisfy a Boolean expression

I need to replace all integers k in a list with {k} and tried:

EDITED: as a clarification: I mean all integer elements of a list, not all integers in the list, so in the following example, only 4 should be replaced by {4}

(# /; AtomQ[#] -> {#} &) /@ {{{{1, 2}, {1, 3}, {2, 3}}, {3, 2, 1}}, 4}


which gives the result

{{{{1, 2}, {1, 3}, {2, 3}}, {3, 2, 1}} /;
AtomQ[{{{1, 2}, {1, 3}, {2, 3}}, {3, 2, 1}}] -> {{{{1, 2}, {1,
3}, {2, 3}}, {3, 2, 1}}}, 4 /; AtomQ[4] -> {4}}


the command

(# -> {#}) & /@ {1, {2}}


works fine (i.e. encloses all elements in brackets). Replacements can be restricted via conditionals according to Mathematica documentation.

I am not clear on why

(# /; AtomQ[#] -> {#} &)


does not have the desired effect of enclosing 4 in brackets (in the example given at the outset)

expr = {{{{1, 2}, {1, 3}, {2, 3}}, {3, 2, 1}}, 4};


You can also get the desired result by Mapping List on expr with level spec {-1}

Map[List, expr, {-1}]

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


Level[expr, {-1}]

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


Update:

"as a clarification: I mean all integer elements of a list, not all integers in the list, so in the following example, only 4 should be replaced by {4}":

You can use the replacement rule x_?AtomQ :> {x} (or x_ /; AtomQ[x] :> {x}) and level specification 1 in Replace:

Replace[
{Sin[xx],
xx,
1 + xx,
{{{1, 2}, {1, 3}, {2, 3}}, {3, 2, 1}},
{5},
4},
x_?AtomQ :> {x},
1]

{Sin[xx],
{xx},
1 + xx,
{{{1, 2}, {1, 3}, {2, 3}}, {3, 2, 1}},
{5},
{4}}

• Thanks, I was not sufficiently clear in the question. I added an edit to clarify the intent. – Mike Mar 5 at 15:53
• @Mike, please see the update. – kglr Mar 5 at 17:34
• Thanks, very clear. – Mike Mar 6 at 9:41

Try either of the following:

list = {{{{1, 2}, {1, 3}, {2, 3}}, {3, 2, 1}}, 4};

Replace[list, n_Integer :> {n}, 1]
Replace[list, n_?NumberQ :> {n}, 1]

(* Out: {{{{1, 2}, {1, 3}, {2, 3}}, {3, 2, 1}}, {4}} *)


Your expression (# /; AtomQ[#] -> {#} &) is a function that generates (somewhat malformed) conditional rules; it is not "a function that gets applied conditionally", as you may have intended. See for instance the result of the following:

(# /; AtomQ[#] -> {#} &)@ 2

(* Out: 2 /; AtomQ[2] -> {2} *)

• Thanks, I was not sufficiently clear in the question. I added an edit to clarify the intent. – Mike Mar 5 at 15:53
• @Mike see edited version of my answer – MarcoB Mar 5 at 15:58
• Thanks, that works! – Mike Mar 6 at 9:41