Hello World
print("Hello, world!")
Fibonacci Numbers
const N = 10
def fibonacci(n: Int) Int {
if n <= 1 ->
return n;
return fibonacci(n - 1) + fibonacci(n - 2);
}
print(fibonacci(N).Str()); // 55
FizzBuzz
def main() {
for i in range(100) {
print(fizzbuzz(i));
}
}
def fizzbuzz(n: Int) Str {
if n % 3 == 0 && n % 5 == 0 {
return "FizzBuzz";
}
if n % 3 == 0 ->
return "Fizz";
if n % 5 == 0 ->
return "Buzz";
return n.Str();
}
Queue class using Generics
class LoggedQueue<T> {
backing_list: List<T>,
// static method as it doesn't take a 'self' parameter
def make_empty<S>() ->
// implicit return using '->', and return type is inferred
new LoggedQueue<S> {
backing_list: List.empty!<S>()
},
// instance methods take an untyped 'self' parameter
def push(self, item: T) LoggedQueue<T> {
self.backing_list.push(item);
print("added item " + self.len().Str());
return self;
}
def pop(self) T {
if self.len() < 1 ->
panic("pop on empty list");
let val = self.backing_list.remove_at(0).unwrap();
print("popped item " + self.len().Str());
return val;
}
def len(self) ->
self.backing_list.len()
}
def main() {
let q = LoggedQueue.make_empty!<Int>()
.push(5)
.push(6);
print("process: " + q.pop().Str()); // 5
print("then: " + q.pop().Str()); // 6
}
First-class / lambda functions
// all functions can be used as values
def double_mapper(num: Int, _index: Int) Int {
return num * 2;
}
def main() {
let my_list = range(5).List();
// specify the type of the new list using generics
let doubled = my_list.map!<Int>(double_mapper);
// gives same value as 'doubled'
let _doubled_b = my_list.map!<Int>(
// lambda function shorthand for 'double_mapper'
fn (a: Int, _: Int) -> a * 2
);
// iterator support with 'for' loops
for i in doubled {
print(i.Str()); // 0, 2, 4, 6, 8
}
}