print("Hello World!")
var doors = List.repeat(100, false)
for i in 0...99: {
for j in i...99 by i + 1: {
doors[j] = !doors[j]
}
}
# The type must be specified since the List starts off empty.
var open_doors: List[Integer] = []
doors.each_index(|i|
if doors[i]: {
open_doors.push(i + 1)
}
)
print("Open doors: {}.".format(open_doors))
enum TreeObject {
TreeValue(String),
TreeList(TreeObject...)
define as_string: String {
match self: {
case TreeValue(v):
return v
case TreeList(l):
var result = "["
var size = l.size() - 1
for i in 0...size: {
result = "{}{}".format(result, l[i].as_string())
if i != size: {
result = result ++ " "
}
}
return result ++ "]"
}
}
}
stdout.write("Here's a JSON-like enum value as a string: ")
print(
TreeList(
TreeList(
TreeValue("abc"),
TreeValue("def")
),
TreeValue("1"),
TreeValue("2"),
TreeList(
TreeList(
TreeValue("0")
)
)
).as_string()
)
var math_ops = ["+" => (|a: Integer, b: Integer| a + b),
"-" => (|a, b| a - b),
"*" => (|a, b| a * b),
"/" => (|a, b| a / b)]
define rpn(input: String): Result[String, List[Integer]]
{
var values = input.split(" ")
var stack: List[Integer] = []
foreach v in values: {
with v.parse_i() as Some(s): {
s |> stack.push
else:
if stack.size() < 2: {
return Failure("Stack underflow.")
}
var right = stack.pop()
var left = stack.pop()
try: {
var op_fn = math_ops[v]
var op_value = op_fn(left, right)
stack.push(op_value)
except KeyError:
return Failure("Invalid operation {}.".format(v))
except DivisionByZeroError:
return Failure("Attempt to divide by zero.")
except Exception:
return Failure("Unexpected error from op {}.".format(v))
}
}
}
return Success(stack)
}
var lines = [
"1 2 3 4 * + -",
"2 2 2 2 * *",
"*",
"1 2 ?"
]
foreach l in lines: {
print("{}: {}".format(l, rpn(l)))
}
import (Coroutine) coroutine
define factorial_co(co: Coroutine[Integer, Unit], num: Integer) {
var f = 1
for i in 2...num + 1: {
co.yield(f)
f *= i
}
}
define create_tasks(source: List[Integer]): List[Coroutine[Integer, Unit]]
{
print("Creating {} tasks:".format(source.size()))
for i in 0...source.size() - 1: {
var s = source[i]
print("Task {} will last {} rounds.".format(i, s))
}
var result = source.map(|m| Coroutine.build_with_value(factorial_co, m))
return result
}
var task_list = [
2,
4,
1,
3,
] |> create_tasks
var total = task_list.size()
var round = 1
while 1: {
var results = task_list.map(Coroutine.resume)
var remaining = task_list.select(Coroutine.is_waiting)
.size()
if remaining == 0: {
break
}
print("\nRound {0} with {1} tasks.".format(round, remaining))
for i in 0...results.size() - 1: {
with results[i] as Some(s): {
print("Task {}: factorial({}) = {}".format(i, round, s))
}
}
round += 1
}