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: {0}.".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 = "{0}{1}".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(" ").reject(|r| r.is_space() )
var stack: List[Integer] = []
for i in 0...values.size() - 1: {
var v = values[i]
match v.parse_i(): {
case Some(number):
stack.push(number)
case None:
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 {0}.".format(v))
except DivisionByZeroError:
return Failure("Attempt to divide by zero.")
}
}
}
return Success(stack)
}
var lines = [
"1 2 3 4 * + -",
"2 2 2 2 * *",
"*",
"1 2 ?"
]
lines.each(|l| print("{0}: {1}".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 {0} tasks:".format(source.size()))
for i in 0...source.size() - 1: {
var s = source[i]
print("Task {0} will last {1} 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: {
var r = results[i]
match r: {
case Some(s):
print("Task {0}: factorial({1}) = {2}".format(i, round, s))
case None:
}
}
round += 1
}