JoeStrout's picture
Upload data files
f7e5a14 verified
{chapterHead: "Day 9: Slice and Scripts", startingPageNum:93}
{width: "50%"}
![](Chapter9.svg)
Q> If you do not have courage, you may not have the opportunity to use any of your other virtues.
Q>— Samuel L. Jackson (actor and producer)
A> **Chapter Objectives**
A> - Learn how to extract a section of a list or a string.
A> - See the many ways in which this "slicing" can be useful.
A> - Learn to write a longer script as a file, so you can run it again and again.
We saw in the last chapter how you could access any element of a list or string by putting its 0-based index in square brackets. We're going to build on that in some really cool ways, so let's start with a quick review. Fire up command-line MiniScript, and try the following at the REPL:
```
s = "Howdy world!"
s[0]
```
That should print "H", since the character in `s` with 0 letters to its left is "H". What would `s[3]` print? What about `s[-1]`, recalling that negative indexes count from the end of the string? Check each of these in the REPL to make sure you're right.
D> If you're not at a computer, following along with these examples in the REPL, they are unlikely to stick. Don't waste your time! No runner ever got fast by watching other people run.
Now the coolness begins.
## Slicing
In MiniScript, as well as some other languages (e.g. Python), you can index into a string or list with *two* indexes instead of just one. When you do, you get back the subset that starts at the first index, and goes up to (but not including) the second one. This operation is known as *slicing*, and what you get back is called a *slice*.
slice
: a substring or sublist defined by start and end indexes in a larger string or list
slicing
: the operation of getting a slice: `seq[a:b]`, where `seq` is a string or list, and `a` and `b` are numbers
You get a slice by putting the two indexes together within the square brackets, separated by a colon. Try it:
```
s[0:3]
```
This should print "How", which is the substring starting at `s[0]`, and going up to but not including `s[3]`. Now see if you can get the slice "world", starting with "w" and going up to but not including "!". Go on. I'll wait.
D> At times like this, the REPL is your dearest friend. Even when you are an experienced programmer with decades of skillful code-craft under your belt, when you need to quickly confirm your understanding of some language feature like slicing, there is no better way than launching a REPL and trying a few quick examples.
Did you come up with `s[6:11]`? That gets the job done! But to get that you probably either had to try several times, or count carefully from the beginning of the string. There is another way, using the trick that negative indices count from the end of the string. `s[-1]` is the exclamation point of our string, so you could write:
```
s[6:-1]
```
This returns the substring starting at character 6, and going up to but not including the last character of the string. You can use a negative number with either index, or both, as needed.
In addition to a numeric index (whether negative or not), you can also *omit* either index. If you leave out the first index, the slice starts at the beginning of the string; if you leave out the second index, the slice extends to the end of the string. These are very commonly needed, so this is a convenient shortcut. Suppose you want to get the first five letters of string `s`. You could of course write:
```
s[0:5]
```
but you can also write:
```
s[:5]
```
which you might read out loud as "s (up to 5)". These are equivalent, though the second form is slightly shorter, and makes your intent slightly more clear. The benefit is a bit greater when you omit the second index. Suppose we want to get the slice "world!" from our "Howdy world!" string... but we are too lazy to count how long the string is (or, in a more realistic setting, we can't know how long it is because it may be different on each run). You could do:
```
s[6:s.len]
```
but it's shorter, easier, and faster to do
```
s[6:]
```
which you might read as "s (from 6 to the end)".
These sorts of string operations come up in programming a lot more than you might think. Suppose you had a filename with a three-letter extension, which is something like ".txt" or ".png" or ".jpg". You might want to get the name without the extension, to display a nice name to the user; or you might want to get the extension itself, to figure out what sort of file it is. Both of these are easy, thanks to slicing.
{caption:"Getting the name and file extension from a file name"}
```miniscript
filename = "My Recipes.txt"
name = filename[:-4]
ext = filename[-3:]
```
Enter that in the REPL, and then enter `name` and `ext` by themselves to see what values they have. `filename[:-4]` gets the original string up to (but not including) the 4th character from the end, or in other words, it strips off the last four characters. Conversely, `filename[-3:]` gets the last three characters of the string.
All our examples so far have been with strings, but slicing works with lists, too. For this next batch of examples, let's work with a list of the first ten prime numbers.
```
p = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
```
Now, because we know this list is already sorted, you can use `p[0]` to find the smallest number, and `p[-1]` to find the largest. (Try it!) That much you knew yesterday. But now you can get, say, the *three* smallest prime numbers:
```
p[:3]
```
Similarly, suppose you wanted the list of all primes *except* for the first and last. You only want the ones in the middle. Again with slicing, this is easy:
```
p[1:-1]
```
This gets the slice starting at element 1 (i.e., the one with 1 to its left), and going up to but not including the last one.
## Attack of the Mutant Lists
One important difference between strings and lists is that strings are immutable, while lists are mutable. "Mutable" means "able to be mutated," and "mutated" is just a fancy word for "changed."
mutable
: describes an object with data that can be changed: in MiniScript, lists and maps
immutable
: describes an object that can't be changed, but only replaced: strings and numbers
You've been mutating lists since you first saw them (i.e. yesterday), with methods like `.push`. Here's another way to mutate a list: replace any element with a new value.
```
p[3] = 42
```
Try that, and then examine `p` to see what it contains. It looks the same as before, except element 3 (the one with 3 items to its left) has been replaced with 42. However, it's important to note that you can *not* replace a slice this way.
{caption:"This doesn't work."}
```miniscript
p[3:6] = [1,2,3]
```
Try it. At the time of this writing, at least, it doesn't work.
D> It's possible that this feature will be added to MiniScript someday. It's a sensible thing to want, and wouldn't break any existing code.
And you also can't mutate a string.
{caption:"This also doesn't work (with strings)."}
```miniscript
s[2] = "x"
```
Of course you can always assign a *new* string to a string variable. When you do something like `s = s.upper`, that is exactly what you're doing. That's not mutating the string; it's just replacing it with a different one. It's the same with numbers, for that matter; there is no way to *change* a number, but you can always assign a variable a new number, replacing its previous value, as in `x = x + 1`.
Because lists are mutable, you have to be a little careful sometimes. When you do something like `q = p`, it is not creating a new list; it is simply making `q` refer to the same list that `p` already referred to. The list itself lives off in the computer's memory somewhere, and has variables like `p` and `q` that refer to it. The list is actually deleted only when there are no more references to it. So, of course, it doesn't matter what variable you use to mutate the list; all references point to the same thing. Try this:
```
q = p
q[0] = "hey"
p
p.push "ho!"
q
```
{pageBreak}
The results will not be surprising, as long as you remember that `p` and `q` do not *contain* a list; they only *refer* to a list. Assignment copies the reference, but does not make a new list.
{width:"50%"}
![](listRefs.svg)
So what do you do when you need to make a copy of a list? For example, suppose you want to keep your original list, but also make a copy that is slightly different. Here slicing comes to the rescue again. It turns out that slicing *always* gets you a new list, even if the range of the slice covers the entirety of the original list. So, you could create a complete copy of list `p` by using
```
q = p[0:p.len]
```
...but, as you learned above, you can omit the first index when it is 0 and omit the last one when it is the length of the list or string. So the standard solution looks like this:
```
q = p[:]
q.push "I'm unique!"
p
q
```
{gap:20}
{width:"62.37%"}
![](listCopy.svg)
Think of `p[:]` as an idiom — a standard way of phrasing a concept in a language. The concept in this case is making a complete copy. You might even read this out loud as "copy of p", though if you forget and need to work it out at first, "p (from the beginning to the end)" is fine too.
## Programs as Text Files
So far in this book, we've written MiniScript code in two contexts: in the Try-It! page on the web, and in the REPL of command-line MiniScript. Both of these are great for short bits of code, but not so great for larger programs. The Try-It! page has a code limit (currently about 2000 characters), and of course typing in a REPL gets to be pretty difficult for loops or `if` blocks that are more than a few lines long.
So it's time to learn to code the way professional programmers do: using a separate code editor! In our case, any text editor will do. But this being the modern world, let's make sure we are clear on the difference between a text editor and a word processor.
text editor
: a program that edits plain text (.txt) files. Examples on Windows include Notepad, Notepad++, and GEdit; examples on Mac include TextEdit and BBEdit
word processor
: a program that edits formatted documents. Microsoft Word is the most widely known word processor, but Apple Pages is another example
While both kinds of applications are superficially similar in how they look and work, what they do is fundamentally different. Text files are fairly universal, but word processors all have their own proprietary format, and their documents are generally not usable in any other program. So, when programming, you will need to use a text editor.
A few examples of text editors are given above. If you're on Windows, Microsoft Notepad is a simple text editor that comes with the operating system, and is perfectly adequate. Many people prefer Notepad++, which is a free replacement that has some more powerful features. The situation on Mac is similar: the built-in TextEdit app will do, though I recommend BBEdit, which is powerful and free (though it has some additional for-pay features you probably won't need). On Linux, your distribution probably came with a graphical text editor, and command-line editors (vi, vim, emacs, nano, etc.) also work fine. There are many other text editors for all platforms, and any of them will work fine, so don't worry too much about which to choose.
Pick one, and create a new file. Enter the following text.
{caption:"Our first MiniScript source file!"}
```miniscript
print "MiniScript is"
for i in range(1, 5)
print "really " * i
end for
print "COOL!"
```
Save this file to disk as "cool.ms" (though the file extension is arbitrary, it's common practice to use ".ms" for MiniScript files). Pay attention to where you save it; you're going to need to know its file path for the next step.
Now the fun part. Open up a new terminal or shell window, or if you are already running command-line MiniScript, enter `exit` (or press control-C) to exit. Now you're back at the shell prompt. As before, enter the path to your command-line MiniScript executable; but before you press Enter or Return, hit the spacebar, and then enter the path to your *cool.ms* text file. (On some systems, you can drag the file icon from Finder or File Explorer right into the terminal/shell window, and it will enter the path for you — try that and see if it works!) Then hit Enter/Return. The result should look something like this.
```terminal
$ ./miniscript ~/DailyPurge/cool.ms
MiniScript is
really
really really
really really really
really really really really
really really really really really
COOL!
$
```
The `$` above is my Unix shell prompt; yours will probably be something different, but that's OK. The line `./miniscript ~/DailyPurge/cool.ms` is the Unix command I typed in to launch command-line MiniScript, and give it the path to my *cool.ms* file. MiniScript read that file, executed the code in it, and then exited (returning me to my `$` shell prompt).
If you see the program output above, then well done! You wrote your very first program in a file, and then ran that program on the command line. Now you have the ability to make your programs as long as they need to be, with the full power of whatever text editor you like, the ability to store them with your backup system, mail them to collaborators, and all those other great things you can do with disk files.
If you didn't see that output, then let's get to the bottom of it before moving on. If MiniScript didn't launch at all (i.e., you got only an error in response to your command), then you probably got the path to MiniScript incorrect. Review and reproduce the work you did yesterday, until you're able to get command-line MiniScript to run. It's also possible you forgot to put a space between the path to MiniScript and the path to your program; make sure to hit the spacebar in between these.
If it launched, printed its version info, and then immediately exited without printing anything else, then you probably got the path to your *cool.ms* file incorrect. Double-check each part of the path. Remember that Windows uses backslashes (`\\`) to separate each part; Mac and Linux use forward slashes (`/`). Also try the trick of dragging the file icon into your shell/terminal window, if you didn't already.
D> You may want to use the `cd` (change directory) shell command to change your current working directory to wherever you stored your *cool.ms* file. Then, after the path to miniscript and a space, you can simply enter *cool.ms*, or the name of any other script in that directory, without having to type the full path.
{pageBreak}
A> **Chapter Review**
A> - You learned how to get a slice of a list or string.
A> - You noticed that lists can be mutated, and found a way to make a copy of a list when you need one.
A> - You created a MiniScript program using a text editor, and ran it using command-line MiniScript.
{gap:340}
{width:"25%"}
![](chinchilla-02.svg)