原文作者:高峰
A interpreter language implementation in Go
Write an Interpreter in Go source code.
Monkey interpreter language which is implemented Go language. After typing monkey
in terminal, you get into the monkey
programming language.
1 $ ./monkey
2 Hello $Username! This is Monkey programming language!
3 Feel free to type in commnd
4 Enter "exit()" or CTRL+C to quit command interface
5 >>>
using let
as keyword, each line ends with ;
.
1 >>>let a = 3;
2 >>>let b = 1.2;
3 >>>a+b
4 4.2
monkey
supports all basic arithmetic operation of int
and float
types. int
type is represented by int64
and float
type is represented by float64
.
1 >>> let a = 3;
2 >>> let b = 1.2;
3 >>> a + b
4 4.2
5 >>> a - b
6 1.8
7 >>> a * b
8 3.6
9 >>> a / b
10 2.5
monkey
contains two builtin containers: array
and map
.
array is a list which organizes items by linear sequence. But types of items can be different from each other.
1 >>> let a = [1, 2.3, "array"];
2 >>> a
3 [1, 2.3, array]
4 >>> let b = push(a, "another");
5 >>> b
6 [1, 2.3, array, another]
map is treated as key-value
container. please attention to that only boolean
, int
and string
types can be used as key.
1 >>> let a = {"name":"moneky", true:1, 7:"sevent"};
2 >>> a
3 {name: monkey, true: 1, 7: seven}
4 >>> a["name"]
5 monkey
6 >>> a[true]
7 1
8 >> a[7]
9 seven
10 >>>let b = set(a, 8, "eight");
11 >>> b
12 {name: moneky, true: 1, 7: sevent, 8: eight}
len
yield the length of builtin containers.
first
yield the first element of array.
last
yield the last element of array.
rest
yield an array which excludes the first element.
push
push an elements into the array.
set
insert key value pair into the map
puts
print literal value of objects.
monkey
use fn
as the definition of function. Apart from regular function using, monkey
also includes high order function.
1 >>>let add = fn(a, b) { return a + b;};
2 >>> add(1,2)
3 3
4 >>>let addTwo = fn(a,b, f) { return 2 + f(a, b);};
5 >>>addTwo(1,2, add)
6 5
monkey
supports if-else statements.
1 >>> let max = fn(a, b) { if (a > b) { return a;} else { return b; } };
2 >>> max(1, 2)
3 2
monkey
support for-loop statement.
1 >>> let sum = fn(x) { let i = 1; let sum = 0; for (i < x) { let sum = sum + i; let i = i+1; } return sum; };
2 >>> sum(100)
3 4950
To make monkey
interpreter language to be more powerfull, it is deserved improving it.
版权申明:内容来源网络,版权归原创者所有。除非无法确认,我们都会标明作者及出处,如有侵权烦请告知,我们会立即删除并表示歉意。谢谢。