Zyn0.1.0

Collections

Zyn has lists, maps and ranges, with a rich set of functions to work with them.

#Lists

A list holds values in order. [a, b, c] makes a list that can't change (read-only):

let primes = [2, 3, 5, 7, 11]
println(primes)
println(primes.size)
println(primes[0])
println(primes.last())
println(primes.contains(7))
println(primes.indexOf(5))
Output
[2, 3, 5, 7, 11]
5
2
11
true
2

Reading past the end stops the program with an error:

let letters = ["a", "b"]
println(letters[2])
Error
Runtime error: Index 2 is out of bounds for a List of size 2
  --> main.zyn:2:16
  |
2 | println(letters[2])
  |                ^

#Lists that change

mutableListOf() makes a list you can add to, remove from and change. When it starts empty, say what it will hold:

let tasks = mutableListOf<String>()
tasks.add("write docs")
tasks.add("fix bug")
tasks.insert(0, "coffee")
tasks[2] = "fix two bugs"
println(tasks)
tasks.removeAt(0)
println(tasks)
println(tasks.remove("write docs"))
println(tasks)
Output
[coffee, write docs, fix two bugs]
[write docs, fix two bugs]
true
[fix two bugs]

The variable is a let (it always points at the same list), but the list itself can change. toMutableList() makes a changeable copy of any list:

let fixed = [3, 1, 2]
let copy = fixed.toMutableList()
copy.add(0)
println(fixed)
println(copy)
Output
[3, 1, 2]
[3, 1, 2, 0]

#Working with lists

These functions return new lists; the original never changes. Lambdas with one parameter can call it it.

let numbers = [5, 3, 8, 1, 9, 2]

println(numbers.filter { it > 4 })
println(numbers.map { it * 10 })
println(numbers.sorted())
println(numbers.sortedDescending())
println(numbers.take(2))
println(numbers.drop(4))
println(numbers.sum())
println(numbers.average())
println(numbers.max())
println(numbers.count { it % 2 == 0 })
println(numbers.any { it > 8 })
println(numbers.all { it > 0 })
println(numbers.first { it > 5 })
println(numbers.chunked(4))
Output
[5, 8, 9]
[50, 30, 80, 10, 90, 20]
[1, 2, 3, 5, 8, 9]
[9, 8, 5, 3, 2, 1]
[5, 3]
[9, 2]
28
4.666666666666667
9
2
true
true
8
[[5, 3, 8, 1], [9, 2]]

#More ways to transform

data Person(name: String, city: String, age: Int)

let people = [
    Person("Ada", "London", 36),
    Person("Grace", "New York", 85),
    Person("Alan", "London", 41),
]

println(people.map { it.name }.joinToString(", "))
println(people.sortedBy { it.age }.map { it.name })
println(people.maxBy { it.age }.name)
println(people.sumOf { it.age })
println(people.groupBy { it.city }.keys)
println(people.fold(0) { total, p -> total + p.age })
println([[1, 2], [3]].flatten())
println(["a b", "c"].flatMap { it.split(" ") })
println([1, 1, 2, 3, 3].distinct())
println(["x", "y"].mapIndexed { i, s -> "{i}{s}" })
Output
Ada, Grace, Alan
[Ada, Alan, Grace]
Grace
162
[London, New York]
162
[1, 2, 3]
[a, b, c]
[1, 2, 3]
[0x, 1y]

#Pipes

Every one of these works with the pipe operator too, which reads well for longer chains:

let words = ["kiwi", "apple", "fig", "banana", "cherry"]
let result = words
    |> filter { it.length > 3 }
    |> sortedBy { it.length }
    |> map { it.uppercase() }
    |> joinToString(" < ")
println(result)
Output
KIWI < APPLE < BANANA < CHERRY

The full list is in the standard library.

#Maps

A map connects keys to values. [key: value] makes a read-only map, and [:] an empty one:

let capitals = ["France": "Paris", "Japan": "Tokyo"]
println(capitals["Japan"])
println(capitals["Peru"])
println(capitals.size)
println(capitals.keys)
println(capitals.values)
println(capitals.containsKey("France"))
Output
Tokyo
null
2
[France, Japan]
[Paris, Tokyo]
true

Looking up a key that isn't there gives null, so the result's type is nullable (String? here). Use ?? for a default: capitals["Peru"] ?? "unknown". See Null safety.

#Maps that change

let stock = mutableMapOf<String, Int>()
stock["apples"] = 10
stock["pears"] = 4
stock["apples"] = (stock["apples"] ?? 0) - 3
stock.remove("pears")
println(stock)
Output
[apples: 7]

#Going through a map

for key, value in map loops over the entries, in the order they were added. Map functions take lambdas with a key and a value:

let scores = ["Ada": 92, "Grace": 78, "Alan": 85]
for name, score in scores {
    println("{name}: {score}")
}
println(scores.filter { _, score -> score > 80 })
println(scores.map { name, score -> "{name[0]}{score}" })
println(scores.count { _, score -> score < 80 })
Output
Ada: 92
Grace: 78
Alan: 85
[Ada: 92, Alan: 85]
[A92, G78, A85]
1

#Counting with a map

let text = "the cat and the hat and the bat"
let counts = mutableMapOf<String, Int>()
for word in text.split(" ") {
    counts[word] = (counts[word] ?? 0) + 1
}
println(counts)
Output
[the: 3, cat: 1, and: 2, hat: 1, bat: 1]

#Ranges

a..b is the whole numbers from a to b, including b; a..<b stops before b. Ranges work with most list functions:

println((1..5).toList())
println((0..<5).map { it * it })
println((1..100).filter { it % 7 == 0 }.take(3))
println((1..10).step(3).toList())
println((1..4).sum())
println((1..10).contains(11))
Output
[1, 2, 3, 4, 5]
[0, 1, 4, 9, 16]
[7, 14, 21]
[1, 4, 7, 10]
10
false

#Strings as collections

A string's characters can be looped over, indexed and turned into a list:

let word = "level"
println(word.toList())
println(word.toList().distinct())
println(word == word.reversed())
Output
[l, e, v, e, l]
[l, e, v]
true