Here is a souped up version of @b3m2a1's answer that supports UpTo
, corrects a couple bugs, and adds error messages. I used the name Inspantiate
because I couldn't resist (probably something like FromSpan
would be better):
Inspantiate[max_, span_Span] := Module[{res = Catch[iList[max, span], "SpanFailure"]},
res /; res =!= $Failed
]
iList[max_, span:Span[a_, b_, c_:1]] := Module[{x, y, z},
x = Replace[a,
{
n_Integer :> If[Abs@n>max || n==0,
Message[Inspantiate::take, a, b, HoldForm[Range[1,max]]];
Throw[$Failed, "SpanFailure"],
Mod[n, max+1]
],
All -> 1,
UpTo[n_Integer?Positive] :> Min[n,max],
_ :> (Message[Inspantiate::span, span]; Throw[$Failed, "SpanFailure"])
}
];
y = Replace[b,
{
n_Integer :> If[Abs@n>max || n==0,
Message[Inspantiate::take, a, b, HoldForm[Range[1,max]]];
Throw[$Failed, "SpanFailure"],
Mod[n, max+1]
],
All -> max,
UpTo[n_Integer?Positive] :> Min[n,max],
_ :> (Message[Inspantiate::span, span]; Throw[$Failed, "SpanFailure"])
}
];
z = Replace[c,
{
All -> If[x<=y, 1, -1],
Except[_Integer] :> (Message[Inspantiate::span, span]; Throw[$Failed, "SpanFailure"])
}
];
Range[x,y,z]
]
Bug fixes:
spanConvert[10, All;;All]
Inspantiate[10, All;;All]
Range[10][[All;;All]]
{10}
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
spanConvert[10, -5;;]
Inspantiate[10, -5;;]
Range[10][[-5;;]]
{}
{6, 7, 8, 9, 10}
{6, 7, 8, 9, 10}
Error messages:
Inspantiate[3, 5;;7]
Range[3][[5;;7]]
Inspantiate::take: Cannot take positions 5 through 7 in Range[1,3].
Inspantiate[3, 5 ;; 7]
Part::take: Cannot take positions 5 through 7 in {1,2,3}.
{1, 2, 3}[[5 ;; 7]]
If you come across a Span
specification where Inspantiate
behaves differently from Range[span]
, please let me know.
Range @@ sp
(see also theApply
function). $\endgroup$ – nben May 17 '17 at 18:57n
... E.g. whensp = 3;;
. $\endgroup$ – kjo May 17 '17 at 19:02Range @@ Replace[sp, All -> n, {1}]
$\endgroup$ – nben May 17 '17 at 19:19All
:Range @@ Replace[ If[Length[s] == 3 && s[[3]] === All, ReplacePart[s, 3 -> -1], s], All -> n, {1}]
$\endgroup$ – nben May 17 '17 at 19:55