|
D.1 Understanding Clusters
|
Often when programming there is a need to combine multiple variables into a
single named object. Doing so makes it easier to keep track of your variables
and adds clarity to your code. In Sheerpower, we call this object a CLUSTER.
Some programming languages call these a
struct or a
vector.
Each cluster is given a name and a list of variables associated with that
name. These variables are sometimes also called
cluster members or
fields.
Simple clusters have no rows. They are one-dimensional and are typically used
to store related information about a single overall concept. For example,
below is a cluster that stores the types of food that one has at meal
time:
cluster meals: protein$, liquid$, carb$
meals->protein$ = "Eggs"
meals->liquid$ = "Tea"
meals->carb$ = "Toast"
Notice that the syntax for referencing cluster variables is:
clustername->variablename
If you have multiple clusters all based on the same "root" cluster, such as
MEALS, you can define the root cluster once and then reference it when
defining related clusters. In this example, we first define a MEALS cluster
and then use it to further define breakfast, lunch, and dinner clusters.
cluster meals: protein$, liquid$, carb$
cluster breakfast using meals
breakfast->protein$ = "Eggs"
breakfast->liquid$ = "Tea"
breakfast->carb$ = "Toast"
cluster lunch using meals
lunch->protein$ = "Chicken"
lunch->liquid$ = "Coffee"
lunch->carb$ = "Rice"
cluster dinner using meals
dinner->protein$ = "Steak"
dinner->liquid$ = "Wine"
dinner->carb$ = "Potatoes"
If you have a routine that requires a lot of data passed into it, using a
cluster is a great way to pass in the data.
The
print cluster CLUSTERNAME, list statement shows the names of each
cluster member and their value. If the member is a string, then inside of
() is also shown the length of the string.