In this section we’ll take a look at a data structure which is very useful - the list. We met it very briefly before in the section on randomisation when we randomly chose from a list of notes to play:
play choose([50, 55, 62])
In this section we’ll explore using lists to also represent chords
and scales. First let’s recap how we might play a chord. Remember that
if we don’t use sleep
, sounds all happen at the same time:
play 52
play 55
play 59
Let’s look at other ways to represent this code.
One option is to place all the notes in a list: [52, 55, 59]
. Our
friendly play
function is smart enough to know how to play a list of
notes. Try it:
play [52, 55, 59]
Ooh, that’s already nicer to read. Playing a list of notes doesn’t stop you from using any of the parameters as normal:
play [52, 55, 59], amp: 0.3
Of course, you can also use the traditional note names instead of the MIDI numbers:
play [:E3, :G3, :B3]
Now those of you lucky enough to have studied some music theory might recognise that chord as E Minor played in the 3rd octave.
Another very useful feature of a list is the ability to get information out of it. This may sound a bit strange, but it’s no more complicated than someone asking you to turn a book to page 23. With a list, you’d say, what’s the element at index 23? The only strange thing is that in programming indexes usually start at 0 not 1.
With list indexes we don’t count 1, 2, 3… Instead we count 0, 1, 2…
Let’s look at this in a little more detail. Take a look at this list:
[52, 55, 59]
There’s nothing especially scary about this. Now, what’s the second
element in that list? Yes, of course, it’s 55
. That was easy. Let’s
see if we can get the computer to answer it for us too:
puts [52, 55, 59][1]
OK, that looks a bit weird if you’ve never seen anything like it
before. Trust me though, it’s not too hard. There are three parts to the
line above: the word puts
, our list 52, 55, 59
and our index
[1]
. Firstly we’re saying puts
because we want Sonic Pi to print the
answer out for us in the log. Next, we’re giving it our list, and
finally our index is asking for the second element. We need to surround
our index with square brackets and because counting starts at 0
, the
index for the second element is 1
. Look:
# indexes: 0 1 2
[52, 55, 59]
Try running the code puts [52, 55, 59][1]
and you’ll see 55
pop up
in the log. Change the index 1
to other indexes, try longer lists and
think about how you might use a list in your next code jam. For example,
what musical structures might be represented as a series of numbers…