Mathematica has a number of functions that return not only the end result or a single match, but all results. Such functions are called *List . Application:
- Foldlist
- Nestlist
- Replacelist
- Composelist
What I am missing is the MapList function.
For example, I want:
MapList[f, {1, 2, 3, 4}]
{{f [1], 2, 3, 4}, {1, f [2], 3, 4}, {1, 2, f [3], 4}, {1, 2, 3, f [4 ]}} I need a list item for each function application:
MapList[ f, {h[1, 2], {4, Sin[x]}}, {2} ]
{h [f [1], 2], {4, Sin [x]}}
{h [1, f [2]], {4, Sin [x]}}
{h [1, 2], {f [4], Sin [x]}}
{h [1, 2], {4, f [Sin [x]]}}
You can implement this as:
MapList[f_, expr_, level_: 1] := MapAt[f, expr,
However, this is quite inefficient. Consider this simple case and compare these timings :
a = Range@1000 ;
This illustrates that, on average, MapList about 38X slower than the aggregate collection of function mapping for each item in the list and creating the 1000x1000 array.
Therefore, how can MapList be implemented as efficiently as possible?