1
$\begingroup$

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?

$\endgroup$
2
$\begingroup$

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"}
$\endgroup$
  • 2
    $\begingroup$ System`Private`HasAnyCodesQ might be better if the OP cares about things with *Values other than OwnValues. $\endgroup$ – b3m2a1 Aug 5 '17 at 18:27
3
$\begingroup$
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"}
$\endgroup$
  • $\begingroup$ 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. $\endgroup$ – Shane Aug 5 '17 at 17:53
  • 3
    $\begingroup$ Just writing {a, b, c} already turns it into {1, b, c} when run. $\endgroup$ – J. M. will be back soon Aug 5 '17 at 17:56
  • $\begingroup$ I suppose I could use If[NumericQ[#]||ListQ[#]... $\endgroup$ – Shane Aug 5 '17 at 17:57
  • 1
    $\begingroup$ Please see updated andwer with a as a list $\endgroup$ – eldo Aug 5 '17 at 18:06
2
$\begingroup$

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