-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample.lox
More file actions
75 lines (59 loc) · 1.2 KB
/
Copy pathexample.lox
File metadata and controls
75 lines (59 loc) · 1.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
// functions, control flow, recursion
fun factorial(n) {
var res = 1;
for (var i = 2; i <= n; i = i + 1) {
res = res*i;
}
return res;
}
fun fib(n) {
if (n==0) return 0;
if (n==1) return 1;
return fib(n-1)+fib(n-2);
}
// Classes
class Rectangle {
init(x, y) {
this.x = x;
this.y = y;
}
perimeter() {
return this.x*this.y;
}
}
// Inheritence
class Square < Rectangle {
init(side) {
super.init(side, side);
}
}
// Closures, lexical scope
// A function which returns functions which build rectangles with a constant x
fun x_rectangle(x) {
fun y_rectangle(y) {
return Rectangle(x, y);
}
return y_rectangle;
}
fun main() {
print factorial(5);
print fib(10);
// Rectangle
var a = Rectangle(5, 10);
// Square
var b = Square(5);
// Rectangles where x is always 3
var three_rectangle = x_rectangle(3);
var c = three_rectangle(4);
var d = three_rectangle(5);
// printing
print "Perimeter of rectangle(5, 10) is:";
print a.perimeter();
print "Perimeter of square(5) is:";
print b.perimeter();
print "Perimeter of rectangle(3, 4) is:";
print c.perimeter();
print "Perimeter of rectangle(3, 5) is:";
print d.perimeter();
}
main();