A Monkey programming language interpreter from the book Writing An Interpreter In Go by Thorsten Ball.
Monkey supports several basic data types.
let x = 12345;let x = true;
let y = false;let x = "Hello World";Monkey includes a variety of operators for performing arithmetic and comparisons.
You can use the following arithmetic operators: +, -, *, and /.
let x = 1 + 2 - 3 * 4;Strings can be concatenated using the + operator. == and != can be used to
compare two strings.
let x = "Hello" + " " + "World";
if (x == "Hello World") {
// ...
}Monkey supports comparison operators such as >, <, ==, and !=.
let x = 5 > 5;
let y = 5 < 5;
let z = 5 == 5;
let v = 5 != 5;The following table shows the operator precedence in Monkey, from lowest to highest:
| Precedence Level | Operators | Description |
|---|---|---|
| 6 (Highest) | Function calls | Function calls |
| 5 | Prefix -, ! |
Unary operations |
| 4 | *, / |
Multiplication and Division |
| 3 | +, - |
Addition and Subtraction |
| 2 | <, > |
Comparison |
| 1 (Lowest) | ==, != |
Equality |
You can use parentheses to influence the order of executing arithmetic operations.
let x = (2 / (5 + 5));Monkey supports if expressions for flow control. An if expression evaluates
a condition and executes the corresponding block of code.
The syntax for an if expression is as follows:
if (condition) {
// block of code
} else {
// optional else block
}- The
elseblock is optional. - Each block can contain multiple expressions or statements.
- The value of the
ifexpression is the value of the last expression in the executed block.
let x = 10;
let y = 20;
let max = if (x > y) {
x
} else {
y
};In this example, max will be set to 20 because y is greater than x.
Monkey supports functions, which can be defined, assigned to variables, called, and passed as arguments to other functions.
Functions can be defined using the fn keyword:
let add = fn(x, y) {
return x + y;
};The return statement is optional. If omitted, the last expression in the
function block will be returned:
let add = fn(x, y) {
x + y;
};Functions can be called immediately without being assigned to a variable:
let three = fn(x, y) {
x + y;
}(1, 2);Functions in Monkey are first-class objects, meaning they can be passed as arguments to other functions:
let sayHello = fn() {
print("hello");
};
let callTwice = fn(f) {
f();
f();
};
callTwice(sayHello);