Basic Arrays

Our SMS service should examine each incoming SMS and check whether it matches a list of keywords we defined. If a match is found, the corresponding reply should be sent back. Let's assume we initially start with the following keywords and replies:

KeywordReply
partyThe party starts at 8pm!
placeI am at home.
moodJust don't ask.

For instance, if someone sends you an SMS with the text "mood", your phone should automatically reply "Just dont ask.".

In m, we could represent this table as two arrays:

keywords=["party", "place", "mood"];
replies=["The party starts at 8pm!",
         "I am at home.",
         "Just don't ask."]

An array is a collection of values (numbers, strings, other arrays...). The above two statements create two arrays and assign them to the variables keywords and replies.

A few observations may help clarifying:

Single elements of each array can be accessed by indexing :

print keywords[0]
→ party
print replies[2]
→ Just don't ask
print replies[3]
→ ExcIndexOutOfRange thrown
print len(replies) // The number of elements in replies
→ 3

And again a few remarks:

Now that we have keywords and replies defined, how are we going to use them? Remember we want to find the reply for an incoming message. This means we have to search through all keywords. If we find a match, the corresponding reply can be used. In m, we could write something like this:

msg=...; // the incoming message
i=0; // start at the first element
while i<len(keywords) and keywords[i]#msg do
  i++
end;
if i<len(keywords) then
  reply=replies[i];
  // send the reply
end

The above code fragment introduces two very important m control structures, while and if:

As an example, consider msg="place". With i=0, the while condition is true, so i++ is executed, setting i=1. Since keywords[i] now equals msg, the while condition is no longer true. And since i<len(keywords), the reply replies[i] will be sent.


© 2004-2010 airbit AG, CH-8008 Zürich
Document AB-M-TUT-869