# Replacing undefined variables

Here's a MWE of what I want to do:

a = 1;
If[ValueQ[#], #, "Null"] & /@ {a, b, c}
(*Actual: {Null, Null, Null}*)
(*Expected: {1, Null, Null}*)


What am I not understanding about mapping pure functions? Or is my confusion elsewhere?

Using a method similar to the one here:

a = 1;
Reap[Scan[Function[Null, Sow[If[ValueQ[#], #, "Null"]], HoldFirst],
Hold[a, b, c]]][[-1, 1]]
{1, "Null", "Null"}

• SystemPrivateHasAnyCodesQ might be better if the OP cares about things with *Values other than OwnValues. – b3m2a1 Aug 5 '17 at 18:27
Clear[a, b, c]

a = 1;

If[NumericQ[#], #, "Null"] & /@ {a, b, c}


{1, "Null", "Null"}

Or more generally

a = {5, 5};

If[! SymbolQ[#], #, "Null"] & /@ {a, b, c}

{{5, 5}, "Null", "Null"}

• Thanks! Could you explain why it doesn't work with ValueQ? I'd like to use it in cases where a might also be a list. So I basically want to return the variable in all cases except those in which it is undefined, and I'm not sure I can do that with NumericQ. – Shane Aug 5 '17 at 17:53
• Just writing {a, b, c} already turns it into {1, b, c} when run. – J. M. will be back soon Aug 5 '17 at 17:56
• I suppose I could use If[NumericQ[#]||ListQ[#]... – Shane Aug 5 '17 at 17:57
• Please see updated andwer with a as a list – eldo Aug 5 '17 at 18:06

You did say "replace" so here is a Replace solution:

a = 1;

List @@ Replace[Hold[a, b, c], x_ /; ! ValueQ[x] :> "Null", {1}]

{1, "Null", "Null"}


Other Replace methods, should you prefer one of them:

Replace[Unevaluated[{a, b, c}], x_ /; ! ValueQ[x] :> "Null", {1}]

List @@ Replace[Hold[a, b, c], {x_?ValueQ :> x, _ -> "Null"}, {1}]