57 lines
1.7 KiB
Plaintext
57 lines
1.7 KiB
Plaintext
// ===========================================================
|
||
// Bob feature-tour demo
|
||
// – dot-notation for dictionaries & arrays
|
||
// – property assignment (incl. nested)
|
||
// – built-in properties: dict.keys / dict.values
|
||
// arr.length / arr.first / arr.last / arr.empty
|
||
// – tail-call-optimised (TCO) recursion
|
||
// ===========================================================
|
||
|
||
// ---------- 1. Dictionary property access / assignment ----------
|
||
var person = { "name": "Alice", "age": 30 };
|
||
print(person.name);
|
||
print(person.age);
|
||
|
||
// add a brand-new user property
|
||
person.country = "Canada";
|
||
print(person.country);
|
||
|
||
// nested property assignment
|
||
var team = { "lead": { "name": "Bob", "age": 40 } };
|
||
team.lead.age = 41;
|
||
print(team.lead.age);
|
||
|
||
// built-in dictionary properties
|
||
print("dict length = " + team.length);
|
||
print(team.keys);
|
||
print(team.values[0].name);
|
||
|
||
// ---------- 2. Array dot-properties ----------
|
||
var nums = [ 10, 20, 30, 40 ];
|
||
print("len = " + nums.length);
|
||
print("first = " + nums.first);
|
||
print("last = " + nums.last);
|
||
print("empty? " + nums.empty);
|
||
|
||
// dot-properties are read-only; assignment still via index
|
||
nums[0] = 99;
|
||
print(nums.first);
|
||
|
||
// ---------- 3. Tail-call-optimised recursion ----------
|
||
func fibTail(n, a, b) {
|
||
return n <= 0 ? a : fibTail(n - 1, b, a + b);
|
||
}
|
||
|
||
print("Fast TCO fib(90) = " + fibTail(90, 0, 1));
|
||
print("Fast TCO fib(5000) = " + fibTail(5000, 0, 1));
|
||
|
||
// ---------- 4. Compare non-TCO version (stack grows!) ----------
|
||
func fibPlain(n) {
|
||
return n <= 1 ? n : fibPlain(n - 1) + fibPlain(n - 2);
|
||
}
|
||
|
||
print("Slow recursive fib(35) = " + fibPlain(35));
|
||
|
||
// ---------- 5. Summary ----------
|
||
print("All new features demonstrated!");
|