Skip to main content
added 499 characters in body
Source Link
E. Chan-López
  • 31.2k
  • 3
  • 29
  • 50
listlist1 = {42, a, f[1, 2, 3], {1, 2, 3}};

list2 = {2, a, foo[a, b], s + t + u, Rational[1, 3], 
         Complex[5, 6], <|a -> x, b -> y, c -> z|>, DateObject[]};

Grabbing the @eldo's list and using Cases and Map:

listlist1 // Map[Cases[{#}, x_ /; AtomQ[x], {0, ∞}] &]

(*{{42}, {a}, {1, 2, 3}, {1, 2, 3}}*)

Generalizing the solution:

f1[expr_] := ReleaseHold@HoldForm[Attributes][Head[expr]]

f2[expr_] /; f1[expr] =!= {} && AtomQ[expr] || f1[expr] =!= {} 
          && ! AtomQ[expr] := expr /. s1_[s2__] | s2__ :> {s2}

f2[expr_] /; f1[expr] === {} := Cases[{expr}, x_ /; AtomQ[x], {0, ∞}]

f2 /@ list2 === toList /@ list2

(*True*)
list = {42, a, f[1, 2, 3], {1, 2, 3}};

Grabbing the @eldo's list and using Cases and Map:

list // Map[Cases[{#}, x_ /; AtomQ[x], {0, ∞}] &]

(*{{42}, {a}, {1, 2, 3}, {1, 2, 3}}*)
list1 = {42, a, f[1, 2, 3], {1, 2, 3}};

list2 = {2, a, foo[a, b], s + t + u, Rational[1, 3], 
         Complex[5, 6], <|a -> x, b -> y, c -> z|>, DateObject[]};

Grabbing the @eldo's list and using Cases and Map:

list1 // Map[Cases[{#}, x_ /; AtomQ[x], {0, ∞}] &]

(*{{42}, {a}, {1, 2, 3}, {1, 2, 3}}*)

Generalizing the solution:

f1[expr_] := ReleaseHold@HoldForm[Attributes][Head[expr]]

f2[expr_] /; f1[expr] =!= {} && AtomQ[expr] || f1[expr] =!= {} 
          && ! AtomQ[expr] := expr /. s1_[s2__] | s2__ :> {s2}

f2[expr_] /; f1[expr] === {} := Cases[{expr}, x_ /; AtomQ[x], {0, ∞}]

f2 /@ list2 === toList /@ list2

(*True*)
Source Link
E. Chan-López
  • 31.2k
  • 3
  • 29
  • 50

list = {42, a, f[1, 2, 3], {1, 2, 3}};

Grabbing the @eldo's list and using Cases and Map:

list // Map[Cases[{#}, x_ /; AtomQ[x], {0, ∞}] &]

(*{{42}, {a}, {1, 2, 3}, {1, 2, 3}}*)