Basic programming concepts in GAML
This page introduces basic GAML structures: declaring variables, using loops, and manipulating lists. It is intended for readers with some programming experience; links point to reference pages for more detail.
Variablesβ
Declare a variable by writing its type followed by its name. Attributes are declared in global, experiment or species scopes; temporary variables can also be declared inside statement blocks and actions.
typeName myVariableName;
Basic typesβ
The basic GAML types include int, float, string and bool. See data types for the full list.
Each code block below is a separate example. Use <- to assign a value and = to test equality.
int integerVariable <- 3;
float floatVariable <- 2.5;
string stringVariable <- "test"; // single quotes are also accepted: 'test'
bool booleanVariable <- true; // or false
Use write to display a variable value in the console. This example adds a reflex to the modelβs global scope; a reflex runs as part of the agent behavior each step. See behaviors and reflexes for details.
model firstModel
global {
int integerVariable <- 3;
float floatVariable <- 2.5;
string stringVariable <- "test"; // single quotes are also accepted: 'test'
bool booleanVariable <- true; // or false
reflex writeDebug {
write integerVariable;
write floatVariable;
write stringVariable;
write booleanVariable;
}
}
experiment myExperiment {}
write accepts values of different types, including containers.
A variableβs default value depends on its type. For example, an unassigned string can be nil, while an unassigned integer is 0.
reflex update {
string my_string;
write my_string; // this will write "nil".
int my_int;
write my_int; // this will write "0", which is the default value for int.
}
nil is also a literal you can use to initialize your variables (you can learn more about the concept of literal in this page).
reflex update {
string my_string <- "a string";
my_string <- nil;
write my_string; // this will write "nil".
int my_int <- 6;
my_int <- nil;
write my_int; // this will write "0", which is the default value for int.
}
The point typeβ
The point type represents coordinates. A point has x and y coordinates, and can also have a z coordinate. Use braces to declare a point:
point p <- {0.2,2.4};
Read its coordinates with x, y and, when present, z:
point p <- {0.2,2.4};
write p.x; // the output will be 0.2
write p.y; // the output will be 2.4
To change a point, assign it a new point value. For example:
point p <- {0.2,2.4};
p <- p + {0.0,1.0};
write p.y; // the output will be 3.4
Working with unitsβ
When manipulating float values, you can specify the dimension (also called unit) of your value. Dimensions are preceded by # or Β° (exactly the same).
float a <- 5Β°m;
float b <- 4#cm;
float c <- a + b; // c is equal to 5.0399999 (it's not equal to 5.04 because it is a float value, not as precise as int)
Declaring variables with facetsβ
Facets set additional properties on a variable declaration, such as its initial value, bounds or update expression. Write each facet after the variable name or initial value. See variable declarations for the available facets.
type variableName <- initialValue facet1:valueForFacet1 facet2:valueForFacet2;
// or:
type variableName facet1:valueForFacet1 facet2:valueForFacet2;
variableName <- initialValue;
The update facet defines an expression that is reevaluated when the variable updates. This example increments an integer and limits it to the range 0β10:
int integerVariable <- 3 min: 0 max: 10 update: integerVariable+1;
The min and max facets constrain the value to a range:
int integerVariable <- 3 min: 0 max: 10 update: integerVariable+1;
// the result will be 3 - 4 - 5 - 6 - 7 - 8 - 9 - 10 - 10 - 10 - ...
The among facet lists values the variable is allowed to take:
string fruits <- "banana" among: ["pear","apple","banana"];
Operators in GAMAβ
GAML operators compute values or test relationships. The following examples introduce common operator groups:
Mathematical operatorsβ
Arithmetic operators include + (addition), - (subtraction), * (multiplication), / (division) and ^ (power):
// FirstOperand BinaryOperator SecondOperand
// --> ex: 5 * 3; // return 15
int fifteen <- 5 * 3;
Other mathematical operators include cos, sin, tan, sqrt and round:
// UnaryOperator(Operand)
// --> ex: sqrt(49); // return 7.0
float sq <- sqrt(49);
Logical operatorsβ
Logical operators such as and and or combine boolean expressions. The ! operator negates a boolean expression. These operators return boolean values.
// FirstOperand Operator SecondOperand
// --> ex: true or false; // return true
// NegationOperator Operand
// --> ex: !(true or false); // return false
Comparison operatorsβ
Comparison operators return a boolean: != (not equal), < (less than), <= (less than or equal to), = (equal), > (greater than) and >= (greater than or equal to):
// FirstOperand Operator SecondOperand
// --> ex: 5 < 3; // return false
bool cmp <- 5 < 3;
Type casting operatorsβ
You can cast an operand to a special type using casting operator:
// Operator(Operand);
// --> ex: int(2.1); // return 2
int intTwo <- int(2.1);
Other operatorsβ
A lot of other operators exist in GAML. Many operators use a function-like form:
Operator(FirstOperand,SecondOperand,...) --> ex: rnd(1,8);
Other operators use infix or postfix syntax:
FirstOperand Operator SecondOperand --> ex: [6,4,5] contains 5;
Conditional structuresβ
You can write conditionals with if/else in GAML:
if (integerVariable<0) {
write "my value is negative !! The exact value is " + integerVariable;
}
else if (integerVariable>0) {
write "my value is positive !! The exact value is " + integerVariable;
}
else if (integerVariable=0) {
write "my value is equal to 0 !!";
}
else {
write "hey... This is not possible, right ?";
}
GAML also accepts ternary operator:
stringVariable <- (booleanVariable) ? "booleanVariable = true" : "booleanVariable = false";
Loopβ
Use the loop statement to repeat a block of statements. Its facets determine the iteration:
- The facet
times, to repeat a fixed number of times a set of statements:
loop times: 2 {
write "helloWorld";
}
// the output will be helloWorld - helloWorld
- The facet
while, to repeat a set of statements while a condition is true:
loop while: true {
}
// without a break or another exit, this loop does not terminate
- The facet
from/to, to repeat a set of statements while an index iterates over a range of values with a fixed step of 1:
loop i from: 0 to: 5 {
write i;
}
// the output will be 0 - 1 - 2 - 3 - 4 - 5
- The facet
from/tocombine with the facetstepto choose the step:
loop i from: 0 to: 5 step: 2 {
write i;
}
// the output will be 0 - 2 - 4
- The facet
overto browse containers, described in the next section.
loop i over: [0, 2, 4] {
write i;
}
// the output will be 0 - 2 - 4
Use break to exit a loop early.
Manipulate containersβ
The previous sections presented the "simple" types of variable. GAML also provides several container types, such as list, matrix, map or pair. Only the list container is described here: the others are covered in the section about datatypes.
How to declare a list?
A list declaration can specify the element type or let GAML infer it from the values:
list<int> listOfInt <- [5,4,9,8];
list listWithoutType <- [2,4.6,"oij",["hoh",0.0]];
How to know the number of elements of a list?
To know the number of elements of a list, you can use the operator length that returns the number of elements (note that this operator also works with strings).
int numberOfElements <- length([12,13]); // will return 2
int numberOfElements <- length([]); // will return 0
int numberOfElements <- length("stuff"); // will return 5
There is another operator, empty, that returns you a boolean telling you if the list is empty or not.
bool isEmpty <- empty([12,13]); // will return false
bool isEmpty <- empty([]); // will return true
bool isEmpty <- empty("stuff"); // will return false
How to get an element from a list?
To get an element from a list by its index, you have to use the operator at (nb: it is indeed an operator and not a facet, so no ":" after the keyword).
int theFirstElementOfTheList <- [5,4,9,8] at 0; // this will return 5
int theThirdElementOfTheList <- [5,4,9,8] at 2; // this will return 9
How to know the index of an element of a list?
You can know the index of the first occurrence of a value in a list using the operator index_of.
You can know the index of the last occurrence of a value in a list using the operator last_index_of.
int result <- [4,2,3,4,5,4] last_index_of 4; // result equals 5
int result <- [4,2,3,4,5,4] index_of 4; // result equals 0
How to know if an element exists in a list?
You can use the operator contains (return a boolean):
bool result <- [{1,2}, {3,4}, {5,6}] contains {3,4}; // true
How to insert/remove an element to/from a list?
Use add to insert elements, put to set an element at an index, and remove to delete an element. Examples:
list<int> list_int <- [1,5,7,6,7];
remove from:list_int index:1; // remove the 2nd element of the list
write list_int; // the output is : [1,7,6,7]
remove item:7 from:list_int; // remove the 1st occurrence of 7
write list_int; // the output is : [1,6,7]
add item:9 to: list_int at: 2; // add 9 in the 3rd position
write list_int; // the output is : [1,6,9,7]
add 0 to: list_int; // add 0 in the last position
write list_int; // the output is : [1,6,9,7,0]
put 3 in: list_int at: 0; // put 3 in the 1st position
write list_int; // the output is : [3,6,9,7,0]
put 2 in: list_int key: 2; // put 2 in the 3rd position
write list_int; // the output is : [3,6,2,7,0]
For lists, + appends an element. The - operator removes the first occurrence of the specified element, if present:
list<int> list_int <- [1,5,7,6,7];
list_int <- list_int + 8;
write list_int; // the output is : [1,5,7,6,7,8]
list_int <- list_int - 7;
write list_int; // the output is : [1,5,6,7]
How to add 2 lists?
Use + to concatenate two lists:
list<int> list_int1 <- [1,5,7,6,7];
list<int> list_int2 <- [6,9];
list<int> list_int_result <- list_int1 + list_int2;
How to browse a list?
You can use the facet over of a loop:
list<int> exampleOfList <- [4,2,3,4,5,4];
loop i over: exampleOfList {
write i;
}
// the output will be 4 - 2 - 3 - 4 - 5 - 4
How to filter a list?
If you want to get all the elements of a list that fulfill a particular condition, you need the operator where. In the condition, you can design all the elements of a particular list by using the pseudo-variable each as followed:
list<int> exampleOfList <- [4,2,3,4,5,4] where (each <= 3);
// the list is now [2,3]
Other useful operators for the manipulation of lists:
Here are some other operators which can be useful to manipulate lists: sort, sort_by, shuffle, reverse, collect, accumulate, among. Please read the GAML Reference if you want to know more about those operators.
Random valuesβ
Models often need random values.
To get a random value in a range, use the operator rnd. You can use this operator in many ways:
int var0 <- rnd(2); // var0 is 0, 1, or 2
float var1 <- rnd(1000) / 1000; // var1 is between 0 and 1 in increments of 0.001
float var2 <- rnd(3.4); // var2 is between 0.0 and 3.4
point var3 <- rnd({2.0, 4.0}, {2.0, 5.0, 10.0}, 1); // x = 2.0, y = 2.0, 3.0, or 4.0; z is between 0.0 and 10.0 in increments of 1.0
float var4 <- rnd(2.0, 4.0, 0.5); // var4 is between 2.0 and 4.0 in increments of 0.5
int var5 <- rnd(2, 4); // var5 is 2, 3, or 4
int var6 <- rnd(2, 12, 4); // var6 is 2, 6, or 10
point var7 <- rnd({2.5, 3, 0.0}); // x is between 0.0 and 2.5, y between 0.0 and 3.0, and z is 0.0
point var8 <- rnd({2.0, 4.0}, {2.0, 5.0, 10.0}); // x = 2.0, y is between 2.0 and 4.0, and z between 0.0 and 10.0
float var9 <- rnd(2.0, 4.0); // var9 is between 2.0 and 4.0
Use the operator flip if you want to pick a boolean value with a certain probability:
bool result <- flip(0.2); // result will have 20% of chance to be true
Use shuffle to randomize a list or among to sample one or more elements:
list TwoRandomValuesFromTheList <- 2 among [5,4,9,8];
// the list will be for example [5,9].
GAML also provides probability distributions such as gauss, poisson, binomial and truncated_gauss.