I use Range
a lot. Is there any syntactic shortcut for it, or do you always have to spell it out?
3 Answers
If you want a nicer layout for Range
you could try the Notation package:
Notation is a bit picky about the definition code of your notation. It has to go manually via its templates. That's why I used a picture above. The following code should work when copied:
<< Notation`
CellPrint@Cell[BoxData[
RowBox[{"InfixNotation", "[",
RowBox[{
TemplateBox[{"\[TripleDot]"},
"NotationTemplateTag"], ",", "Range"}], "]"}]], "Input"]
After executing those two lines, a third one will appear which must be executed as well. After that you can use the \[TripleDot]
character to define ranges:
5 \[TripleDot] 9
{5, 6, 7, 8, 9}
If you just want shorter code you can define:
r = Range;
r@5
r[3, 9, 2]
{1, 2, 3, 4, 5}
{3, 5, 7, 9}
-
$\begingroup$ The
Notation
package method is very nice. Just a shame that, as things are, you must still either type, literally, "[\TripleDot]
" or else create an Escape alias for it. (Unfortunately,Esc ... Esc
is already preempted for\[Ellipsis]
. $\endgroup$– murrayCommented Oct 20, 2013 at 22:43 -
$\begingroup$ @LCarvalho, did you even test your correction to ensure that it works? $\endgroup$ Commented Dec 27, 2016 at 12:49
-
$\begingroup$ @J.M. An error occurred while pasting. Excuse me. $\endgroup$ Commented Dec 27, 2016 at 13:09
The reference page for gives variations which utilize default arguments:
Range[20]
Range[1,20]
Range[1,20,1]
An alternative for this usage is Array
Array[#&,20]
If you are after a list of numbers, you could use Table
Range[6,20,2]
Table[i,{i,6,20,2}]
But if you are just using the output of Range
as indices for Part
then you might want to look at Span
f[[Range[6,20,2]]]
f[[6;;20;;2]]
-
$\begingroup$ Using the shortcut
;;
forSpan
does make code shorter than directly usingRange
for indexing. But @Sjoerd C. de Vries's method using the Notation package and\[TripleDot]
makes indexing expressions more closely resemble traditional mathematical notation. $\endgroup$– murrayCommented Oct 20, 2013 at 22:46
On my laptop I can get the symbol "®" with "Alt-r". So the following code using the infix notation (see Infix) is very similar to the answer of Sjoerd C. de Vries, but much easier to set-up.
In[77]:= ® = Range;
In[78]:= 4~®~7
Out[78]= {4, 5, 6, 7}
In[79]:= Range[4, 7]
Out[79]= {4, 5, 6, 7}
In[80]:= 4~Range~7
Out[80]= {4, 5, 6, 7}
R=Range;
. You could also try typing R and then pressing Command+(Shift)+K (or the equivalent windows keys) for autocompletion and templates. Yet another option may be to check out Halirutan's IntelliJIdea plugin. $\endgroup$r = Range;
? $\endgroup$