The language / Arrays and hashes
Start here01
The language02
- 01The basics
- 02Values and numbers
- 03Variables
- 04Calls and expressions
- 05Conditions and loops
- 06Strings
- 07Arrays and hashes
- 08Classes and records
- 09Traits and enums
- 10Blocks
- 11Methods
- 12Imports and exports
- 13Foreign files
- 14Failures
Programs and the world03
- 01Files, input and output
- 02JSON, time, URLs and random numbers
- 03Html and forms
- 04Templates: Ochre
- 05Built-in methods
Kiln04
02 The language / 07
Arrays and hashes
Collections of one type each, which are values: copied, never shared.
Arrays and hashes are how a program keeps many values together. An array keeps them in order and finds them by position; a hash finds each one by a key. Each holds one type of element, so you always know what comes out of it. And both are values: when you assign one or pass it to a method, the other side gets its own copy, so nothing elsewhere in the program can change yours.
- Array
[Int]: elements in order, read by index from 0.- Hash
{String: Int}: keys in the order they were added, read withget.- One type each
- All elements share a type; for a hash, all keys share one and all values share one.
- Values
- Copied when assigned or passed, never shared.
Arrays
An array is a list of values in square brackets. You read an element by its position, counting from 0, and an array kept in a var can grow with push or have an element replaced:
var scores = [90, 72, 85]
print(scores[0]) # prints 90
print(scores.length) # prints 3
scores.push(60)
scores[1] = 75
print(scores) # prints [90, 75, 85, 60]One type per array
An array's type is written [ElementType], and every element has that type. Mixing kinds is an error, even whole numbers with decimals, so whatever you take out of an array is always one known thing:
const names = ["Ada", "Grace"] # a [String]
const mixed = [1, "two"] # error: array elements must all have the same type; found an Int and a String
const numbers = [1, 2.5] # error: array elements must all have the same type; found an Int and a FloatThe type is worked out from the elements. An empty array has none to go by, and an array that contains nil can't say what else it may hold, so both need their type written where they're declared:
var names: [String] = []
var maybe: [Int?] = [1, nil, 3]
var items = [] # error: can't tell the type of an empty array here; give it a type where it's declared, like 'var items: [Int] = []'Where the type is already known (a parameter, a return type, a typed variable), [] takes it from there: total([]) works for def total(items: [Int]).
- Arrays can hold arrays:
[[1, 2], [3]]is a[[Int]]. - Mind where the
?goes.[Int]?is "an array, or nil";[Int?]is "an array whose elements may be nil".
Reading and changing
| Write | Means |
|---|---|
items[0] | the first element |
items[items.length - 1] | the last element |
items.length | the number of elements |
items[0] = value | replace an element (only in a var) |
items.push(value) | add to the end (only on a var) |
a + b | a new array with a's elements, then b's (same type) |
a == b | same length and equal elements, in order |
Indexes start at 0 and must be Ints. Reading or replacing past the end is an error, never nil, and so is a negative index. The message says what went wrong and how to reach the last element:
const items = [1, 2, 3]
print(items[3]) # error: index 3 is out of bounds for an array of length 3 (the last index is 2)
print(items[-1]) # error: index -1 is negative; indexes start at 0 (for the last element, use items[items.length - 1])Changing an array needs a var. A const array can't change at all: no push, no items[0] = .... And because push changes the array it's called on, it must be called on a variable: [1, 2].push(3) is an error.
Write items[0] and items.length with no space before [ or ..
Arrays are values
Assigning an array, or passing it to a method, gives an independent copy. Changing the copy never changes the original:
var original = [1, 2]
var copy = original
copy.push(3)
print(original) # prints [1, 2]
print(copy) # prints [1, 2, 3]This is what lets you read a program one variable at a time. Once an array is yours, the only code that can change it is code that changes your variable; handing it to a method or storing it elsewhere can't reach back into it.
It also means a method can't change the array passed to it, since parameters are constants. To build a changed version, copy it into a var and return that:
def with_zero(items: [Int]): [Int]
var result = items
result.push(0)
return result
endHashes work the same way, and so do objects.
Looping over an array
To do something with every element, give each a block. Blocks covers each and the other methods that take one, like map and filter:
def total(items: [Int]): Int
var sum = 0
items.each do (n)
sum = sum + n
end
return sum
end
print(total([1, 2, 3])) # prints 6Hashes
A hash maps keys to values, keeping keys in the order they were added. Use one to look things up by name or number:
var ages = {"Ada": 36, "Grace": 85}
print(ages.get("Ada")) # prints 36
print(ages.get("Bob")) # prints nil
print(ages.get("Bob", fallback: 0)) # prints 0
ages.set("Bob", to: 40)
print(ages) # prints {"Ada": 36, "Grace": 85, "Bob": 40}Types and literals
A hash type is written {KeyType: ValueType}. Keys are String or Int; all keys share one type, and all values share one type. As with arrays, an empty hash, or one with nil values, needs its type written:
const numbers = {1: "one", 2: "two"} # a {Int: String}
var scores: {String: Int} = {} # empty: the type must be written
var maybe: {String: Int?} = {"a": nil} # nil values need a written typeKeys in {...} must be written-out strings or numbers. A name is an error, because {name: 36} could be read two ways: as the key "name", or as the value of the variable name. Rather than guess, Hematite asks you to say which:
const ages = {name: 36} # error: write the key as a string, like {"name": ...}; to use the variable 'name' as a key, use .set(name, to: value)Between a key and its value goes :, never =>, and a key can't appear twice:
const settings = {"theme": "dark", "language": "da"}A longer literal may span lines, with a trailing comma.
Reading and changing
Hashes are read and changed only through methods, never with [...]. Writing ages["Ada"] or ages["Ada"] = 1 is an error that points you to .get and .set.
| Write | Means |
|---|---|
ages.get("Ada") | the value, or nil if the key is missing |
ages.get("Ada", fallback: 0) | the value, or 0 if the key is missing |
ages.has("Ada") | true if the key exists |
ages.set("Bob", to: 40) | add the key at the end, or replace its value in place (only on a var) |
ages.remove("Bob") | remove the key if it exists (only on a var) |
ages.length | the number of keys |
ages.keys | the keys as an array, in order |
ages.values | the values as an array, in order |
a == b | same keys with equal values, in any order |
The key's type is checked: ages.get(1) on a {String: Int} is an error. Hashes are values, like arrays: a copy is independent of the original, and everything in Arrays are values holds for them too.
When a key might be missing
For a missing key, .get(key) gives nil, so its result can't be used as a value until that's been ruled out. A key you forgot to check shows up as an error when the file is checked, with the two usual ways out in the message:
const ages = {"Ada": 36}
print(ages.get("Bob") + 1) # error: ages.get("Bob") might be nil here; check it first with 'if ages.has("Bob")', or give a fallback: ages.get("Bob", fallback: ...)There are three ways to rule it out.
Check with .has(key) first. It counts as the check for .get(key) with the same key, until the hash or the key's variable changes. The key must be a variable or a written-out value:
var counts = {"a": 1}
const word = "a"
if counts.has(word)
counts.set(word, to: counts.get(word) + 1)
else
counts.set(word, to: 1)
end
print(counts) # prints {"a": 2}Use a key that came from the hash itself. A key taken from the hash's own keys always has a value: the parameter of prices.keys.each do (name) or prices.each do (name, price), or an element of const names = prices.keys. This holds until the hash, or the array of keys, changes:
const prices = {"apple": 3, "pear": 5}
prices.keys.each do (name)
print(prices.get(name) * 2)
end
# prints 6
# prints 10
const names = prices.keys
const first = names[0]
print(prices.get(first) + 1) # prints 4Give a fallback, of the hash's value type, to use when the key is missing:
var counts = {"a": 1}
const word = "b"
counts.set(word, to: counts.get(word, fallback: 0) + 1)
print(counts) # prints {"a": 1, "b": 1}Looping over a hash
each on a hash passes each key and its value, in the order the keys were added:
const prices = {"apple": 3, "pear": 5}
prices.each do (name, price)
print("#{name}: #{price}")
end
# prints apple: 3
# prints pear: 5