Too often I have seen the programs of inexperienced users greatly slowed by using Position in an iterative fashion, when far faster would have been to compute a look-up table for positions beforehand.
Mathematica provides such functionality for Nearest and Interpolation "out of the box" with the syntax of function[data] along with dedicated functions NearestFunction and InterpolatingFunction.
There is no equivalent with Position[data] producing a PositionFunction object. I observe that Position appears to be used more often than either of the other functions so this seems like a regrettable omission. Two complications I can think of are:
the levelspec of
Positionthe handling of patterns
Based on this I ask:
What other complications are there for creating a PositionFunction?
How best can such a function be implemented?
How can the utility and performance of the function be maximized?
All limitations considered would such a function be valuable?
Why is there no such functionality in Mathematica?
Answer
I see no mention of the new-in-10 PositionIndex in the other answers, which takes a list (or association) of values and returns a 'reverse lookup' that maps from values in the list to the positions where they occur:
In[1]:= index = PositionIndex[{a, b, c, a, c, a}]
Out[1]= <|a -> {1, 4, 6}, b -> {2}, c -> {3, 5}|>
It doesn't take a level spec yet (though I do want to add that).
In any case, the returned association is already a function in some sense because of the function application way of doing key lookup in associations.
So in the above example you could write index[a] to get a list of places where a occurred.
Comments
Post a Comment