4

Have a tricky Mathematica problem. I am trying to build up functions from data to automate my processes with a minimum of hardcoding.

So let's say I have some data:

myList = {"e1", "e2", "e3", "e4"};

I want these strings to become symbols that are arguments to a function.

Here's how I do that:

args = Map[ToExpression[# <> "_"] &, myList] /. List -> Sequence

which returns:

Sequence[e1_, e2_, e3_, e4_]

All good. Now I make myself a list of symbols that I can use inside my function, say with Map:

variables = Map[ToExpression[#] &, myList]

which returns:

{e1, e2, e3, e4}

Now when I reference the symbol directly in a function:

Clear[f];
f[args] := Block[{},
e1
]

f[10, 20, 30, 0] returns 10, which is perfect. But, I don't want to refer to my symbols directly. Rather I want to refer to them indirectly:

Clear[f];
f[args] := Block[{},
variables[[1]]
]

f[10, 20, 30, 0] returns e1, which is not what I want. I want it to return 10 as above. I've tried a number of variations of the function, but none work. Can someone help?

Thanks in advance,

George Danner

kglr
  • 394,356
  • 18
  • 477
  • 896
GeorgeD
  • 41
  • 2

1 Answers1

5

Using Pattern and PatternSequence;

ClearAll[f, args];
myList = {"e1", "e2", "e3", "e4"};
args = Map[ToExpression[# <> "_"] &, myList] /. List -> PatternSequence
(* or PatternSequence @@ (Pattern[#, _] & /@ (ToExpression /@ myList)); *)
(* or PatternSequence @@ (Pattern[#, _] & /@ (Symbol /@ myList)); *)

f[a : args] := Block[{}, {a}[[1]]]
f[10, 0, 2, 3]
(* 10 *)
kglr
  • 394,356
  • 18
  • 477
  • 896