In my code, I generate a list of integers called numlist
. Here is an example numlist
:
numlist = Sort[Table[RandomInteger[{1, 100}], {3}]]
which gives, for example, the output:
{17, 74, 96}
I would like to write a function generateFun
that, using numlist
as input, generates the following function myfun
:
myfun[int_Integer] := Which[
int == 17, 1,
int == 74, 2,
int == 96, 3
]
In other words, myfun
takes an integer and returns the position of that integer in numlist
. numlist
is created at the beginning of the code and does not change during a given execution; however, a new execution will in general create a new list of integers numlist
. The length of numlist
varies (it is not guaranteed to be 3), although this fact is not present in the minimal working example that I gave above.
I could bypass generateFun
and simply use this function myfun2
:
myfun2[int_Integer, numlist_] := First[First[Position[numlist, int]]]
which returns the position of int_
in numlist_
. However, since I will need to call the function (myfun
or myfun2
) many times (~1,000,000 times), I think that calling Position
every time may be quite expensive -- since numlist
, once generated, does not change during the execution.
Do you have any advice on how I can generate the Which
expression automatically from numlist
?