Interpreter with support for class, linq, sql, net, http, fmt, json and A realtime syntax highlighting REPL.
Interpreter with support for class, linq, sql, net, http, fmt, json and A realtime syntax highlighting REPL.
This project is no longer being maintained. All the contents have been moved to magpie.
Chinese version: 中文
Monkey is a toy language interpreter, written in Go. It has C-style syntax, and is largely inspired by Ruby, Python, Perl and c# It support the normal control flow, functional programming and object oriented programming. It also has a REPL with realtime syntax highlighter.
This is a sample program using monkey language:
…or, to run a program:
monkey path/to/fileMonkey support two kinds of single line comment and also block comment.
// this is a single line comment
# this is another single line comment
/* This is a
block comment.
*/Monkey supports 9 basic data types: String, Int, UInt, Float, Bool, Array, Hash, Tuple and Nil
s1 = "hello, 黄" # strings are UTF-8 encoded
s2 = `hello, "world"` # raw string
i = 10 # int
u = 10u # uint
f = 10.0 # float
b = true # bool
a = [1, "2"] # array
h = {"a": 1, "b": 2} # hash
t = (1,2,3) # tuple
n = nilIn monkey, there are mainly eleven types of constants(Literals).
…Variables in Monkey could start with the keyword let, or nothing with the
form variable=value.
let a, b, c = 1, "hello world", [1,2,3]
d = 4
e = 5
姓 = "黄"You can also use Destructuring assignment.
Note, the left-hand side must be included using the '()'.
//righ-hand side is an array
let (d,e,f) = [1,5,8]
//d=1, e=5, f=8
//right-hand side is a tuple
let (g, h, i) = (10, 20, "hhf")
//g=10, h=20, i=hhf
//righ-hand side is a hash
let (j, k, l) = {"j": 50, "l": "good"}
//j=50, k=nil, l=good
Note however, if you do not use the keyword let, you could not do multiple variable assignments.
Below code is not correct:
//Error, multiple variable assignments must be use `let` keyword
a, b, c = 1, "hello world", [1,2,3]Note:Starting from Monkey 5.0,when the decalared variable already exists, it's value will be overwritten:
let x, y = 10, 20;
let x, y = y, x //Swap the value of x and y
printf("x=%v, y=%v\n", x, y) //result: x=20, y=10let also support the placeholder(_), when assigned a value, it will just ignore it.
let x, _, y = 10, 20, 30
printf("x=%d, y=%d\n", x, y) //result: x=10, y=30Keywords are predefined, reserved identifiers that have special meanings to the compiler. They cannot be used as identifiers. Below is a list of reserved keywords
You can use the builtin int(), uint(), float(), str(), array(), tuple(), hash, decimal functions for type conversion.
let i = 0xa
let u = uint(i) // result: 10
let s = str(i) // result: "10"
let f = float(i) // result: 10
let a = array(i) // result: [10]
let t = tuple(i) // result:(10,)
let h = hash(("key", "value")) // result: {"key": "value}
let d = decimal("123.45634567") // result: 123.45634567You could create a tuple from an array:
let t = tuple([10, 20]) //result:(10,20)Similarly, you could also create an array from a tuple:
let arr = array((10,20)) //result:[10,20]You could only create a hash from an array or a tuple:
//create an empty hash
let h1 = hash() //same as h1 = {}
//create a hash from an array
let h1 = hash([10, 20]) //result: {10 : 20}
let h2 = hash([10,20,30]) //result: {10 : 20, 30 : nil}
//create a hash from a tuple
let h3 = hash((10, 20)) //result: {10 : 20}
let h4 = hash((10,20,30)) //result: {10 : 20, 30 : nil}qw(Quote word) keywordThe qw keyword is like perl's qw keyword. When you want to use a lot of quoted strings,
the qw keyword can make it a lot easier for those strings.
for str in qw { //allowed 'qw' pair is '{}', '<>', '()'
println('str={str}')
}
newArr = qw(1,2,3.5) //array with string values, not number values.
fmt.printf("newArr=%v\n", newArr)enum keywordIn mokey, you can use enum to define constants.
…In monkey, if you have some resources you want to release/free/close, e.g. close opended file, close network connection etc,
you can use the using statement just like c#.
// Here we use 'using' statement, so we do not need to call infile.close().
// When finished running 'using' statement, it will automatically call infile.close().
using (infile = newFile("./file.demo", "r")) {
if (infile == nil) {
println("opening 'file.demo' for reading failed, error:", infile.message())
os.exit(1)
}
let line;
let num = 0
//Read file by using extraction operator(">>")
while (infile>>line != nil) {
num++
printf("%d %s\n", num, line)
}
}In monkey, you are free to define some operators, but you cannot overwrite predefined operators.
Note: Not all operators could be user defined.
Below is an example for showing how to write User Defined Operators:
//infix operator '=@' which accept two parameters.
fn =@(x, y) {
return x + y * y
}
//prefix operator '=^' which accept only one parameter.
fn =^(x) {
return -x
}
let pp = 10 =@ 5 // Use the '=@' user defined infix operator
printf("pp=%d\n", pp) // result: pp=35
let hh = =^10 // Use the '=^' prefix operator
printf("hh=%d\n", hh) // result: hh=-10fn .^(x, y) {
arr = []
while x
=X
++
+=
+X
--
-=
->
-X
>=
<>
>X
<=
<<
<X
!=
!~
!X
*=
**
*X
..
..
.X
&=
&&
&X
|=
||
|X
^=
^X
> In the table above, `X` could be `.=+-*/%&,|^~},!?@#$`
### Integer
In monkey, integer is treated as an object, so you could call it's methods.
Please see below examples:
```swift
x = (-1).next()
println(x) //0
x = -1.next() //equals 'x = -(1.next())
println(x) //-2
x = (-1).prev()
println(x) //-2
x = -1.prev() //equals 'x = -(1.prev())
println(x) //0
x = [i for i in 10.upto(15)]
println(x) //[10, 11, 12, 13, 14, 15]
for i in 10.downto(5) {
print(i, "") //10 9 8 7 6 5
}
println()
if 10.isEven() {
println("10 is even")
}
if 9.isOdd() {
println("9 is odd")
}In monkey, float is also treated as an object, so you could call it's methods. Please see below examples:
f0 = 15.20
println(f0)
f1 = 15.20.ceil()
println(f1)
f2 = 15.20.floor()
println(f2)In monkey, decimal is Arbitrary-precision fixed-point decimal numbers. And the code mainly based on decimal.
Please see below examples:
d1 = decimal.fromString("123.45678901234567") //create decimal from string
d2 = decimal.fromFloat(3) //create decimal from float
//set decimal division precision.
//Note: this will affect all other code that follows
decimal.setDivisionPrecision(50)
fmt.println("123.45678901234567/3 = ", d1.div(d2)) //print d1/d2
fmt.println(d1.div(d2)) //same as above
fmt.println(decimal.fromString("123.456").trunc(2)) //truncate decimal
//convert string to decimal
d3=decimal("123.45678901234567")
fmt.println(d3)
fmt.println("123.45678901234567/3 = ", d3.div(d2))In monkey, you could use [] to initialize an empty array:
emptyArr = []
emptyArr[3] = 3 //will auto expand the array
println(emptyArr)You can create an array with the given size(or length) using below two ways:
//create an array with 10 elements initialized to nil.
//Note: this only support integer literal.
let arr = []10
println(arr)
//use the builtin 'newArray' method.
let anotherArr = newArray(len(arr))
println(anotherArr) //result: [nil, nil, nil, nil, nil, nil, nil, nil, nil, nil]
let arr1 = ["1","a5","5", "5b","4","cc", "7", "dd", "9"]
let arr2 = newArray(6, arr1, 10, 11, 12) //first parameter is the size
println(arr2) //result: ["1", "a5", "5", "5b", "4", "cc", "7", "dd", "9", 10, 11, 12]
let arr3 = newArray(20, arr1, 10, 11, 12)
println(arr3) //result : ["1", "a5", "5", "5b", "4", "cc", "7", "dd", "9", 10, 11, 12, nil, nil, nil, nil, nil, nil, nil, nil]Array could contain any number of different data types. Note: the last comma before the closing ']' is optional.
mixedArr = [1, 2.5, "Hello", ["Another", "Array"], {"Name": "HHF", "SEX": "Male"}]You could use index to access array element.
println('mixedArr[2]={mixedArr[2]}')
println(["a", "b",No open issues yet, or sync has not completed.