Mercurial > hg > truffle
comparison graal/com.oracle.truffle.sl.test/tests/CalcShell.sl @ 13821:b16ec83edc73
Documentation and more refactoring of Simple Language
author | Christian Wimmer <christian.wimmer@oracle.com> |
---|---|
date | Wed, 29 Jan 2014 20:45:43 -0800 |
parents | |
children |
comparison
equal
deleted
inserted
replaced
13820:20e7727588e8 | 13821:b16ec83edc73 |
---|---|
1 function iterations() { | |
2 return 80; | |
3 } | |
4 | |
5 function calcLoop(n) { | |
6 i = 0; | |
7 prev = cur = 0; | |
8 while (i <= n) { | |
9 next = calc(prev, cur, i); | |
10 prev = cur; | |
11 cur = next; | |
12 i = i + 1; | |
13 } | |
14 return cur; | |
15 } | |
16 | |
17 function timing(n) { | |
18 i = 0; | |
19 while (i < 20) { | |
20 start = nanoTime(); | |
21 calcLoop(n); | |
22 end = nanoTime(); | |
23 i = i + 1; | |
24 | |
25 println("** run " + i + ": " + (end - start) + " ns"); | |
26 } | |
27 } | |
28 | |
29 function run(n) { | |
30 firstResult = calcLoop(n); | |
31 println("** first: " + firstResult); | |
32 i = 0; | |
33 while (i < 100) { | |
34 calcLoop(n); | |
35 i = i + 1; | |
36 } | |
37 lastResult = calcLoop(n); | |
38 println("** last: " + lastResult); | |
39 | |
40 if (firstResult != lastResult) { | |
41 println("ERROR: result not stable"); | |
42 } | |
43 } | |
44 | |
45 function help() { | |
46 println("available commands:"); | |
47 println("x: exit"); | |
48 println("c: define the calculation function with the parameters prev, cur, and i"); | |
49 println(" prev and cur start with 0; i is the loop variable from 0 to n"); | |
50 println(" example: 'return cur + i;' computes the sum of 1 to n"); | |
51 println(" example: 'if (i == 0) { return 1; } else { return cur * i; }' computes the factorial of i"); | |
52 println(" example: 'if (i <= 2) { return 1; } else { return prev + cur; }' computes the nth Fibonacci number"); | |
53 println("i: define the number of iterations, i.e, the number n in the examples above"); | |
54 println("r: Run the calculation loop often, and print the first and last result"); | |
55 println("t: Run the calculation loop a couple of time, and print timing information for each run"); | |
56 println("h: Print this help message"); | |
57 println(""); | |
58 } | |
59 | |
60 function main() { | |
61 help(); | |
62 | |
63 while (1 == 1) { | |
64 println("cmd>"); | |
65 cmd = readln(); | |
66 if (cmd == "x" || cmd == "") { | |
67 return; | |
68 } | |
69 if (cmd == "h") { | |
70 help(); | |
71 } | |
72 if (cmd == "c") { | |
73 println("function>"); | |
74 code = readln(); | |
75 defineFunction("function calc(prev, cur, i) { " + code + "}"); | |
76 } | |
77 if (cmd == "t") { | |
78 timing(iterations()); | |
79 } | |
80 if (cmd == "r") { | |
81 run(iterations()); | |
82 } | |
83 if (cmd == "i") { | |
84 println("n>"); | |
85 n = readln(); | |
86 defineFunction("function iterations() { return " + n + "; }"); | |
87 } | |
88 } | |
89 } |