// A tour of everything lux can do today.
// Immutable and mutable bindings.
let name = "Ada"
var score = 0
// Assignment and compound assignment.
score = score + 10
score += 5
// print takes any number of values, separated by spaces.
print("Hello,", name)
print("Score:", score)
// Integer division throws away the remainder; float division keeps it.
print("7 / 2 =", 7 / 2)
print("7.0/2.0 =", 7.0 / 2.0)
print("7 % 2 =", 7 % 2)
// Explicit conversion — lux never coerces silently.
let label = "Score is " + string(score)
print(label)
// Branching.
if score >= 100 {
print("high score!")
} else if score > 0 {
print("not bad")
} else {
print("try again")
}
// Looping.
var n = 0
while n < 5 {
print("n is", n)
n += 1
}
// Booleans and short-circuit logic.
let ready = score > 0 && name != ""
print("ready?", ready)
// Functions: define once, call anywhere — even before they appear in the file.
print("7! =", factorial(7))
func factorial(n: int) -> int {
if n <= 1 {
return 1
}
return n * factorial(n - 1)
}
// Arrays hold many values of one type.
let primes: [int] = [2, 3, 5, 7, 11]
print("primes:", primes, "— first:", primes[0], "— count:", length(primes))
// Loop over an array...
var sum = 0
for p in primes {
sum += p
}
print("sum of primes:", sum)
// ...or over a range, whose end is not included.
for i in 0..3 {
print("tick", i)
}
// Build an array up as you go.
var squares: [int]
for i in 1..6 {
squares += i * i
}
print("squares:", squares)
// Structs group related values into a type of your own.
struct Point {
x: int
y: int
}
let here = Point(x: 3, y: 4)
print("here:", here, "— x is", here.x)
// Enums say a value is exactly one of a fixed set of cases, each able to carry
// its own values. `match` takes them apart, and must cover every case.
enum Shape {
circle(radius: float)
square(side: float)
}
func area(s: Shape) -> float {
return match s {
circle(let r) => 3.14159 * r * r
square(let a) => a * a
}
}
print("circle area:", area(Shape.circle(radius: 2.0)))
print("square area:", area(Shape.square(side: 3.0)))
// There is no null. A missing value is Option<T> — some(x) or none — and a
// fallible one is Result<T, E> — ok(x) or err(reason). match makes you handle
// the empty or failing case, so it can never slip past you.
func firstEven(xs: [int]) -> Option<int> {
for x in xs {
if x % 2 == 0 {
return some(x)
}
}
return none
}
match firstEven([1, 3, 4, 7]) {
some(let x) => print("first even:", x)
none => print("no even number")
}