A monkey language interpreter implementation, from the book Writing an interpreter in Go
let add = fn(x, y) { return x + y; };
let three = add(1, 2);
let arr = [1, true, fn (x) { return x; }];
let one = arr[0];
let add = fn (x, y) = { return x + y; };
let some_hash = {"foo" + "bar": 2, true: add(40, 2)};
let two = some_hash["foobar"];
let meaning_of_life = some_hash[true];
len(X)
: Returns the length of X, can be applied onstring
,array
orhash
.first(X)
: Returns the first element of an array X, ornull
if it has no elements.last(X)
: Returns the last element of an array of X, ornull
if it has no elements.head(X)
: Returns a slice of an array X containing all but the last element, or an empty array if X had no elements.tail(X)
: Returns a slice of an array X containing all but the first element, or an empty array if X had no elements.push(X)
: Adds an element in the last position of an array X.push(...X)
: Prints the value of any amount of arguments, each on a different line.
-
*, /, +, -
: Regular math operators that can be used oninteger
s. -
+
: Other than it's previous use, it can also be used to concatenatestring
.let foobar = "foo" + "bar";
-
[]
: Index operator can be applied toarray
s orhash
es to get the element at the given index.let some_hash = {"foo": "bar"}; let bar = some_hash["foo"];
let numbers = [3, 2, 1]; let one = numbers[2];
!
: Bang operator negates the RHS operand.let not_true = !true; let unchanged = !!true;
The project includes a REPL, which you can use to evaluate monkey
code. You can launch said REPL by running cargo run
.
> let some_hash = {"foo" + "bar": 2 * 2};
[foobar: 4]
> some_hash["foobar"]
4