Basic syntax
A quick look at all of Zyn, with links to the pages that go deeper. Every example runs as it is.
#Program entry point
A file can be a script that runs from top to bottom, or have a main function:
fn main() {
println("Hello, world!")
}Hello, world!
main can also take the command-line arguments: fn main(args: List<String>).
#Printing
println prints a value and a line break; print leaves out the line break.
print("Hello, ")
print("world")
println("!")
println(42)
println()
println([1, 2, 3])Hello, world! 42 [1, 2, 3]
#Functions
A function with a block body uses return. One that is a single expression can use =, and then its return type can be left out.
fn sum(a: Int, b: Int): Int {
return a + b
}
fn product(a: Int, b: Int) = a * b
fn report(a: Int, b: Int) {
println("The sum of {a} and {b} is {sum(a, b)}, their product {product(a, b)}")
}
report(3, 5)The sum of 3 and 5 is 8, their product 15
See Functions.
#Variables
let declares a value that can't be changed; var one that can. The type is inferred from the value, or written after a colon.
let name = "Zyn" // String, can't change
var count = 0 // Int, can change
let ratio: Float = 0.75 // type written out
count += 1
println("{name} {count} {ratio}")Zyn 1 0.75
#Comments
// A comment to the end of the line
/* A comment over
several lines. /* They can be nested. */ */
println("comments are ignored")comments are ignored
#String interpolation
Anything inside { } in a string is an expression whose value goes into the string:
let a = 3
let b = 4
println("{a} + {b} = {a + b}")
println("The name has {"Zyn".length} letters")
println("Braces themselves are written \{like this\}")3 + 4 = 7
The name has 3 letters
Braces themselves are written {like this}See Strings.
#Conditions
if needs no parentheses, and always braces. It's also an expression:
fn maxOf2(a: Int, b: Int): Int = if a > b { a } else { b }
let n = 7
if n % 2 == 0 {
println("{n} is even")
} else {
println("{n} is odd")
}
println(maxOf2(3, 9))7 is odd 9
#Loops
let fruits = ["apple", "banana", "kiwi"]
for fruit in fruits {
println(fruit)
}
for i, fruit in fruits {
println("{i}: {fruit}")
}
var n = 3
while n > 0 {
println(n)
n -= 1
}apple banana kiwi 0: apple 1: banana 2: kiwi 3 2 1
See Control flow.
#Ranges
for i in 1..3 { print("{i} ") } // 1 to 3
println()
for i in 0..<3 { print("{i} ") } // 0 to 2
println()
for i in (0..10).step(5) { print("{i} ") }
println()
println((1..10).contains(4))1 2 3 0 1 2 0 5 10 true
#match
match picks the first branch whose pattern fits. It must cover every case.
fn describe(x: Int): String = match x {
0 -> "zero"
1..<10 -> "small"
_ -> "big"
}
println(describe(0))
println(describe(7))
println(describe(250))zero small big
See Pattern matching.
#Collections
let numbers = [5, 3, 8, 1] // List<Int>, can't change
let ages = ["Ada": 36, "Linus": 54] // Map<String, Int>
let names = mutableListOf<String>() // a list that can change
names.add("Grace")
println(numbers.sorted())
println(numbers.filter { it > 2 }.map { it * 10 })
println(ages["Ada"])
println(names)[1, 3, 5, 8] [50, 30, 80] 36 [Grace]
See Collections.
#Null safety
A type that can be null ends in ?. Zyn makes sure such a value is checked before it's used.
fn findUser(id: Int): String? = if id == 1 { "Ada" } else { null }
let user = findUser(2)
println(user?.length) // null: ?. only calls if there's a value
println(user ?? "nobody") // ?? gives a default
let found = findUser(1)
if found != null {
println(found.uppercase()) // here found is a String
}null nobody ADA
See Null safety.
#Data types and enums
data Point(x: Int, y: Int)
enum Direction { North, East, South, West }
let p = Point(1, 2)
println(p)
println(p.copy(y = 5))
println(p == Point(1, 2))
println(Direction.entries)Point(x=1, y=2) Point(x=1, y=5) true [North, East, South, West]
See Data types and enums.
#Classes
interface Shape {
fn area(): Float
}
class Rectangle(let width: Float, let height: Float) : Shape {
override fn area(): Float = width * height
}
let r = Rectangle(2.0, 3.5)
println(r.area())7.0
#Lambdas and pipes
let square = { x: Int -> x * x }
println(square(5))
// |> passes the value on its left as the first argument of the function on its right
fn double(x: Int): Int = x * 2
println(5 |> double |> square)
println([1, 2, 3, 4] |> filter { it % 2 == 0 })25 100 [2, 4]
#Errors as values
Something that can fail returns a Result: Ok with a value, or Err with an error. try passes an Err on.
fn half(text: String): Result<Int, String> {
let n = try text.toInt()
if n % 2 != 0 { return Err("{n} is odd") }
return Ok(n / 2)
}
println(half("10"))
println(half("7"))
println(half("ten"))Ok(5)
Err(7 is odd)
Err('ten' is not a whole number)See Errors.
#Tests
fn double(x: Int): Int = x * 2
test "doubling" {
assertEq(double(21), 42)
}$ zyn test main.zynRunning 1 test in main.zyn
✓ doubling
1 passed, 0 failedSee Testing.