Span
(;;
) is very useful, but doesn't work with a lot of functions. Given the following input
list = {{"a", "b", "c"}, {"d", "e", "f",
"g"}, {"h", {{"i", "j"}, {"k", "l"}, {"m", "n"}, {"o", "pp"}}}}
We would like
MapAt[Framed, list, 1 ;; 2]
MapAt[Framed, list, {{1, 1}, {2, 2 ;; 3}, {3, 2, 1 ;; 3, 1}}]
to work as expected
Here is my first go at it:
SpanToRange[Span[x_:1,y_:1,z_:1]] := Module[{zNew = z},
If[x>y && z==1, zNew = -1];
Range[x, y, zNew]
] /; And[VectorQ[{z,y,z}, IntegerQ],
And @@ Thread[{z,y,z} != 0]]
helper = Function[list,
Module[{li=list},
If[FreeQ[li, Span], li,
li = Replace[li,s_ /; Head[s] =!= Span :> {s}, {1}];
li = li /. s:_Span :> SpanToRange[s];
Sequence @@ Flatten[
Outer[List, Sequence @@ li],
Depth[Outer[List, Sequence @@ li]]-3]]
]
];
protected = Unprotect[Span, MapAt];
Span /: MapAt[func_, list_, s:Span[x_:1,y_:1,z_:1]]:= MapAt[func,
list, Thread[{SpanToRange[s]}]];
MapAt[func_, list_, partspec_] /; !FreeQ[partspec, Span] := Module[{f,p = partspec},
MapAt[func, list, Join[helper /@ p]]
];
Protect[Evaluate[protected]];
But this is far from finished, and the extended down values should support all valid uses of Span
such as
MapAt[Framed, list, 3 ;;]
MapAt[Framed, list, ;; ;; 2]
MapAt[Framed, list, ;; 10 ;; 2]