5
$\begingroup$

Is it possible to apply function to list elements only if function applicable to element? For example

{1.2, 3, {2.3, 5.4}, null, "fff"}
Floor[%]

gives

{1, 3, {2, 5} ,Floor[null], Floor["fff"]}

but I would like to get

{1, 3, {2, 5} ,null, "fff"}
$\endgroup$
  • 2
    $\begingroup$ f[x_?NumericQ]:=Floor[x]; f[x_]:=x; f /@ list. Or If[NumericQ[#], Floor[#], #]& /@ list $\endgroup$ – Szabolcs Nov 4 '16 at 20:20
  • $\begingroup$ Floor[%] go through nested lists. Is it possible for your solution? $\endgroup$ – Филипп Цветков Nov 4 '16 at 20:24
  • 1
    $\begingroup$ MapAll[f, list] or f//@ list $\endgroup$ – David G. Stork Nov 4 '16 at 20:27
  • 1
    $\begingroup$ Look up Listable. $\endgroup$ – Szabolcs Nov 4 '16 at 20:36
  • $\begingroup$ related: mathematica.stackexchange.com/q/9784/5478 $\endgroup$ – Kuba Nov 15 '16 at 10:09
4
$\begingroup$

It would be the combination of the comments of Szabolcs and David G. Stork

list = {1.2, 3, {2.3, 5.4}, null, "fff"};
f[x_?NumericQ] := Floor[x]; f[x_] := x; f /@ list;
MapAll[f, list]

{1, 3, {2, 5}, null, "fff"}

$\endgroup$
4
$\begingroup$
ClearAll[f]
f = Floor@# /. Floor -> Identity &;

f@{1.2, 3, {2.3, 5.4}, null, "fff"}

{1, 3, {2, 5}, null, "fff"}

f@{1.2, 3, {2.3, "ff"}, null, "fff", Pi}

{1, 3, {2, "ff"}, null, "fff", 3}

If the function returns unevaluated when a 'non-applicable' input is passed, this approach is more convenient as it does not require detailed knowledge of the function's argument requirements.

ClearAll[h]
h[x_] := 500 /; PrimeQ[x]
h[x_] := 500 /; Divisible[x, 3]
h /@ Range[15] /. h -> Identity

{1, 500, 500, 4, 500, 500, 500, 8, 500, 10, 500, 500, 500, 14, 500}

StringLength /@ {"abcabc", "bcdbc", 234} /. StringLength -> Identity

Mathematica graphics
{6, 5, 234}

$\endgroup$
1
$\begingroup$
list = {1.2, 3, {2.3, "ff"}, null, "fff", Pi};

SetAttributes[floor, Listable]

floor[x_] := x /. a_?NumericQ :> Floor @ a

floor @ list

{1, 3, {2, "ff"}, null, "fff", 3}

$\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.