I have a function whose variable are specified by a input parameters of function:
ParametersList1 = {{"a", 1}, {"b", 2}}
ParametersList2 = {{"a", 3}, {"b", 4}}
TestFunction[ParametersList_] := Module[{},
Table[ToExpression[ParametersList[[n]][[1]] <> "=" <> ToString[ParametersList[[n]][[2]]]],
{n, 1, Length[ParametersList]}];
Return[a + b]
]
TestFunction[ParametersList1]
3
TestFunction[ParametersList2]
6
The function works as expected, however, the parameter a and b should not be global. The number of parameters given by ParametersList is not known and I cannot explicitly describe it as Module[{a,b},...]. Is there anyway to define local variables in a dynamic way, for example, something like following?
Module[ToExpression[ParametersList[[All, 1]]],...]
a
orb
explicitly too, you may end up with contex issues for more complicated cases. There are ways to deal with this too but if you are on v10+ then maybevars = <|"a" -> 1, "b" -> 2|>; vars["a"] + vars["b"]
instead ofParametersList1/2
? $\endgroup$a+b
because you don't know that they are calleda
andb
. Why then not just working with the list as it is?Return[Total[ParametersList[[All,2]]]]
$\endgroup$6
forTestFunction[ParametersList2]
? $\endgroup$