I'm trying to construct a function somewhat similar to MapAt
. A basic usage example should look like this:
list = {a, b, c, d};
MapAtSequence[f, list, 2;;3]
(* {a, f[b, c], d} *)
Or with specific numbers and functions
list = {1, 2, 3, 4};
MapAtSequence[Plus, list, 2;;3]
(* {1, 5, 4} *)
I'm not attached to the idea of using Span
, a list of positions may also be ok, but so far I only have the need to apply a function to neighboring elements.
Here's my minimal working example:
MapAtSequence[f_, list_, span_] := Module[{l = list, output},
l[[span]] = f[Sequence @@ l[[span]]];
output = Drop[l, {(First@span) + 1, Last@span}]
]
This appears to work as intended, but is clearly good only for 1D lists. A pitfall awaits me if the applied function generates a list of the same length as the span (see somewhat related question). A similar pitfall awaits if my function generates a Sequence
.
Moreover, I have a feeling this isn't an efficient or elegant way to get the job done. After all, at first glance the task sounds really simple - I need to splice a function into the list, for example go from this:
{a, b, c , d} (* to this: *)
{a, Plus[b, c], d} (* <---| *)
How can I improve my code and generalize it to multidimensional lists?
Edit:
For a certain set of functions such as Plus
and Times
my problem can be formulated in a simpler manner:
How can I replace some neighboring commas in a list to the infix notation of a function, e.g.:
{a, b, c, d, e}
{a, b~Plus~c~Plus~d, e}