4
$\begingroup$

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

$\endgroup$
  • $\begingroup$ Well well Mr. Danner. Good to see you here. $\endgroup$ – kale Oct 1 '14 at 23:15
  • 1
    $\begingroup$ Is it necessary to use SetDelayed ,:=? If you use Set ,=, your function works without any problems. $\endgroup$ – Algohi Oct 1 '14 at 23:59
5
$\begingroup$

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 *)
| improve this answer | |
$\endgroup$
  • $\begingroup$ Thank you @kguler! That works beautifully! $\endgroup$ – GeorgeD Oct 2 '14 at 14:32
  • $\begingroup$ @GeorgeD, my pleasure. You might consider Accepting/Upvoting an answer if you find it useful. $\endgroup$ – kglr Oct 2 '14 at 14:42
  • $\begingroup$ args = Map[ ToExpression[# <> "_"] &, myList]; f[Sequence@@args] := Evaluate[ First@args[[1]] ] seems to do the job also. $\endgroup$ – gwr Oct 2 '14 at 19:34

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.