Maps & Sets
Nostos provides `Map` for efficient key-value storage and `Set` for managing unique collections. Both are immutable by default, promoting predictable data flow.
Maps
Maps are unordered collections of key-value pairs, where keys must be hashable. They offer efficient O(1) average-case lookup, insertion, and deletion. Maps are created using the `%{key: value}` syntax.
main() = {
# Type inference from literal
user = %{"name": "Alice", "city": "New York"} # inferred Map[String, String]
ages = %{"alice": 30, "bob": 25} # inferred Map[String, Int]
# Explicit type declaration (useful for empty maps)
scores: Map[String, Int] = %{}
scores2 = scores.insert("alice", 100)
# Accessing values with get
name = user.get("name") # "Alice"
age = ages.get("alice") # 30
# Inserting/Updating values (returns a new map)
updated_ages = ages.insert("charlie", 35)
updated_user = user.insert("city", "Boston") # updates existing key
# Removing values (returns a new map)
smaller_ages = ages.remove("bob")
println(user) # original map is unchanged
println(updated_ages) # %{...3 entries}
println(scores2) # %{...1 entries}
}
Sets
Sets are unordered collections of unique elements. Like Maps, elements must be hashable. They are useful for membership testing, eliminating duplicates, and performing set operations (union, intersection, difference). Sets are created using the `#{element1, element2}` syntax.
main() = {
# Type inference from literal (duplicates automatically removed)
numbers = #{1, 2, 3, 2, 1, 4} # inferred Set[Int], becomes #{1, 2, 3, 4}
# Explicit type declaration (useful for empty sets)
names: Set[String] = #{}
names2 = names.insert("alice")
# Membership testing
has_two = numbers.contains(2) # true
has_five = numbers.contains(5) # false
# Adding elements (returns a new set)
with_five = numbers.insert(5)
with_five_again = with_five.insert(5) # No change, still 5 items
# Removing elements (returns a new set)
without_two = numbers.remove(2)
println(numbers) # #{...4 items}
println(with_five) # #{...5 items}
println(names2) # #{...1 items}
println(has_two) # true
}