I'd like to make a function that takes a list of variables and returns a corresponding rule list with the current values of the variables. E.g.
x = 1;
y = 2;
VariablesToRules[{x, y, z}]
(* {x -> 1, y -> 2, z -> z} *)
Is this even possible?
I'd like to make a function that takes a list of variables and returns a corresponding rule list with the current values of the variables. E.g.
x = 1;
y = 2;
VariablesToRules[{x, y, z}]
(* {x -> 1, y -> 2, z -> z} *)
Is this even possible?
Update 2
Based on a suggestion by Somos, the following version is nicer. According to what the OP wants:
SetAttributes[variableToRule, {HoldAll, Listable}]
variableToRule[var_] := SymbolName@Unevaluated@var -> var
and according to my original interpretation of the problem:
SetAttributes[variableToRule, {HoldAll, Listable}]
variableToRule[var_] := Module[{val = var}, Clear@var; var -> val]
Update 1
After some comments from the OP, it seems they want instead something like
variableToRule[var_] := SymbolName@Unevaluated@var -> var
instead.
Original Post
Here's a first iteration. First define the helper function,
ClearAll@variableToRule
SetAttributes[variableToRule, HoldAll]
variableToRule[var_] := Module[{val = var}
, Clear@var
; var -> val
]
Then, the function is
ClearAll@variablesToRules
SetAttributes[variablesToRules, HoldAll]
variablesToRules[vars_List] := variableToRule /@ Unevaluated@vars
This uses the trick from this answer.
Then,
x = 1; y = 2; z = 3;
variablesToRules[{x, y, z}]
(* {x -> 1, y -> 2, z -> 3} *)
x and y, etc. in expressions that contain those variables? In that place, you don't want x and y set before-hand. What is it that you are trying to do here? Is this just for display purposes or something? If you keep the variables set, then you will get {1 -> 1, 2 -> 2}.
– march
Feb 06 '19 at 21:02
variableToRule[var_] := SymbolName[Unevaluated@var] -> var seems OK
– Chris K
Feb 06 '19 at 21:02
Block or something?
– march
Feb 06 '19 at 21:10
SymbolName[Unevaluated[]] is an easy enough solution for me!
– Chris K
Feb 06 '19 at 21:14
SetAttributes[variableToRule, {HoldAll, Listable}] and variableToRule[var_Symbol] := SymbolName@Unevaluated@var -> var and variableToRule[var___] := variableToRule[List@var]
– Somos
Feb 06 '19 at 21:37
variableToRule[var_List] := variableToRule @ var makes that work.
– march
Feb 06 '19 at 23:07
Pass in the names of the symbols as strings, and the rest is quite easy:
ClearAll[varsToRules];
varsToRules[s_] := With[{t = Map[Symbol, s]},
s // Apply[ClearAll];
MapThread[Rule, {Symbol /@ s, t}]
];
ClearAll[x, y];
{x, y, z} = {1, 2, 3};
varsToRules[{"x", "y", "z"}]
(* {x -> 1, y -> 2, z -> 3} *)
Clearthem, but it's not clear how to short-circuit the evaluation when you will be feeding a list of variable names to the function rather than just the variable name. – march Feb 06 '19 at 20:34OwnValues /@ Unevaluated@{x, y, z}OK? – xzczd Feb 07 '19 at 03:28