The tour, 5 of 11
Arrays and Maps
Dynamic arrays, Map literals, and std.collections' methods on them.
An array, T[], grows as it’s added to, and is indexed from 0. An index outside it panics, with
the line.
Import std.core
Local scores: Int[] = [70, 85]
scores.Add(92)
scores[0] = 75
Print(scores, scores.Count, scores[2])
Print(scores[0..2]) // a slice: elements 0 and 1Output
[75, 85, 92] 3 92 [75, 85]
A {key: value} literal makes a Map, which keeps its entries in the order they were added.
Import std.core
Local hp = {"grunt": 50, "ogre": 300}
hp["boss"] = 900
For name, value In hp
Print("{name}: {value}")
End For
Print(hp.Get("ogre") ?? 0, hp.Get("dragon") ?? 0)Output
grunt: 50 ogre: 300 boss: 900 300 0
Get gives a Int?, which is Null for a key that isn’t there; ?? gives another value then.
Nullability is a page of its own.
std.collections
Import std.collections brings in the methods arrays have for sorting, searching, and changing
them, which take lambdas, and the other collections: Set, Stack, Queue, Deque, PriorityQueue, and
more.
Import std.core
Import std.collections
Import std.text
Local words = ["pear", "fig", "banana", "kiwi"]
words.Sort()
Print(words)
Local long = words.Filter(Function(w: String) => w.Length > 3)
Print(long)
Local lengths = words.Map(Function(w: String) => w.Length)
Print(lengths)
Local seen = Set<String>()
For w In ["a", "b", "a", "c", "b"]
seen.Add(w)
End For
Print(seen.Count)Output
[banana, fig, kiwi, pear] [banana, kiwi, pear] [6, 3, 4, 4] 3
Next: Structs and Classes.
Report an issue with this page or with FutureBlitz on GitHub.