Start here / Habits that don't carry over
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
01 Start here / 03
Habits that don't carry over
What code often does elsewhere, and what Hematite does instead: worth a read whatever you wrote before.
Everyone arrives with habits from the code they've written before. This page collects the ones that would be mistakes in Hematite, grouped by topic, each with what Hematite does instead. A habit that many languages share is listed once.
Each section says in a few lines how Hematite works there, shows one habit side by side with what to write instead, and lists the rest.
Lines and names
Hematite code has one statement on each line, and every block ends with end. Indentation is layout, which hem fmt keeps right; it never changes what code means. Names are plain ASCII, and their case means nothing. More in the basics.
Not this
Indentation ends a block.
Write this
end ends a block. Indentation is layout, which hem fmt keeps right.
| Habit | In Hematite |
|---|---|
; separates statements | Not allowed. One statement per line. |
{ and } around blocks | end closes a block. |
=begin / =end block comments | Not allowed. Use # on every line. |
A line starting with . or + continues the previous line | Not allowed. End the previous line with the operator instead. |
Names may contain any Unicode (café) | ASCII only. café is an error. |
| Uppercase names are constants | Case means nothing. const makes a variable unchangeable; static makes a value the file's methods and other files can use. |
Numbers and arithmetic
Ints are 64-bit, and / always gives a Float, so you round when you want a whole number. A number that would overflow, or a division by zero, is an error rather than a surprising value. See values and numbers.
Not this
7 / 2 is 3 (Int division).
Write this
7 / 2 is 3.5. / always gives a Float; the whole-number division is 7.quotient(2), which is 3.
| Habit | In Hematite |
|---|---|
| Integers grow without limit | 64-bit. Too-large literals and arithmetic overflow are errors. |
a // b (whole-number division) | a.quotient(b). |
1.0 / 0 is Infinity | Error: division by zero. |
a ** b | Not available. |
x += 1 | x = x + 1. There are no compound assignments. |
+x (unary plus) | Not allowed. Write x. |
0o17, 0x1F, 017 (octal) | Not supported. 017 is just 17. |
1e20.to_s is "1.0e+20" | Prints 1e20. |
x.round(2) with half-to-even or binary surprises | x.round(2) rounds the number as it prints; halves go away from zero. |
Printing
print takes exactly one value on every call, and prints it as it is. To print several values on one line, build a string. See printing.
Not this
print(a, b), an error
Write this
print("#{a} #{b}"). print takes exactly one value.
| Habit | In Hematite |
|---|---|
puts x | print(x). |
println!("{}", x) | print(x), or print("#{x}"). |
puts nil prints an empty line | Prints nil. |
puts alone prints an empty line | Error: print takes exactly 1 argument. |
puts a, b prints each on its own line | Error. Use one print per value. |
Variables
Every variable is declared, with const if it never changes and var if it does, and its type is fixed by its first value. A variable lives only in the block that declares it, and assigning is a statement of its own. See variables.
Not this
x = 1 creates a variable.
Write this
Declare it: const x = 1 or var x = 1. x = 1 only changes an existing var.
| Habit | In Hematite |
|---|---|
let x = 1 | var x = 1; const when it never changes. |
let mut x = 1 | var x = 1. |
val x = 1 | const x = 1. |
x := 1 | const x = 1, or var x = 1 if it changes. |
x = y = 0 | One assignment per line. |
1 + x = 2, (x = 1), foo(x = 1) assign inside an expression | Error. Assign on its own line first. |
| A variable can hold any type over time | Its type is fixed by its first value. var n = 1 then n = 1.5 is an error. |
Variables assigned in an if exist after it | Variables live only in their block. Declare before the if. |
| An inner variable may reuse an outer name | Error: a name can't be declared while another variable with that name is visible. |
Values that might be nil
There is one "nothing", nil, and only a type that says so (Int?, User?) can hold it. There are no shortcuts around a nil: you check with if x != nil, and the checker sees the check, so the code after it can use the value. See nil and optional types.
Not this
x?.y, x ?? y, x ?: y, x!!
Write this
Not available. Check if x != nil first; the checker sees the check.
| Habit | In Hematite |
|---|---|
null and undefined | Only nil. |
None, True, False | nil, true, false. |
let user: User | null = null | var user: User? = nil |
Option<T> | T?, checked with if x != nil. |
user!.name, as casts | Not available. Check if user != nil first; the checker sees the check. |
Calls and methods
Every call has parentheses, even with no arguments, because parentheses are what say a method runs: without them, a name is a value. Every argument after the first is named, every parameter has a type, and a method gives its result with return. See calls and methods.
Not this
transfer(50, savings, checking)
Write this
Every argument after the first is named: transfer(50.0, from: savings, to: checking).
| Habit | In Hematite |
|---|---|
add 1, 2 (a call without parentheses) | Error. Write add(1, 2). |
name.upcase, account.total (calls without arguments) | Error. Write name.upcase(); without parentheses, a name is a value, like a field. |
foo (1) (space before the parenthesis) | Error. Write foo(1). |
foo -1 / x -1 (guessed from spacing) | Error. Write foo(-1) or x - 1. |
def add(a, b) | Every parameter needs a type: def add(a: Int, b: Int): Int. |
function add(a, b), (a, b) => a + b | def add(a: Int, b: Int): Int. Blocks only go to built-in methods. |
def greet without parentheses | def greet(). |
def total(self): | def total(): Int. self isn't a parameter; it's there in every method. |
| The last expression is returned automatically | Write return value. A method with a return type must return on every path. |
| Methods can change their parameters | Parameters are constants. Copy into a var to change. |
def greet(name, loud = false), keyword arguments | def greet(name: String, loud: Boolean = false), called as greet("Ada") or greet("Ada", loud: true). |
| Overloaded methods | One method per name; a default value covers the optional parts. |
*args, **options | Not available yet. |
| Several return values | Return a record. |
Conditions and choices
A condition must be true or false: nothing counts as true by itself. Logic is spelt and, or and not, every if block takes its own lines, and a one-line choice is a value. See conditions and loops.
Not this
Everything except nil and false is truthy: if user.
Write this
Conditions must be true or false. if 0, if nil, if user are errors; write if user != nil.
| Habit | In Hematite |
|---|---|
!x, &&, || | Use not x, and, or. They bind like !, && and || do. |
and/or with unusually low precedence | and/or bind like &&/||: x = a or b assigns a or b. |
AND, OR, NOT, &&, ||, ! | and, or, not, in lowercase only: any other spelling is an error. |
1 < x < 3 fails at runtime (true < 3) | Syntax error: comparisons can't be chained. |
===, and == that converts | == only, between values of the same type: comparing an Int with a String is an error. |
<=>, ===, =~ | Not available. |
elsif | else if, on one line. |
elif | else if. |
unless x | Use if not x. |
until x | Use while not x. |
print(x) if ok (modifier form) | Use a full if ... end block. |
if x then y end on one line | Only as a value: v = if x then a else b. Blocks use separate lines. |
ok ? a : b | if ok then a else b. Never nested. |
x if ok else y | if ok then x else y. |
x = if ok ... end (multi-line if gives a value) | Use the one-line if ... then ... else, or assign inside the branches of an if block. |
Choosing by value
A fixed set of states is an enum, and when chooses between its values. when works only for enums, lists every value, and has no else, so adding a value shows you every place that has to handle it. For other values, use if and else if. See choosing by value.
| Habit | In Hematite |
|---|---|
Symbols like :draft for a fixed set of states | An enum: enum Status with draft on its own line, used as Status.draft. |
case status / when :draft / else | when status / is Status.draft / end, only for enums. Every value must be listed; there is no else. For other values, use if and else if. |
switch | when, for enums; if and else if for anything else. |
match | when, for enums, listing every value; if and else if for anything else. |
when with else | when is only for enums, lists every value, and has no else. |
Loops and blocks
There are two ways to repeat: while, and each with a block. A block is written do (x) ... end, gives its value with return, and goes to a method that runs it; it isn't a value you can keep. See blocks.
Not this
for item in items:
Write this
items.each do (item) ... end.
| Habit | In Hematite |
|---|---|
for i in range(n): | while, with a counter: var i = 0, then i = i + 1 in the loop. |
for i := 0; i < n; i++ | while i < n, with i = i + 1. There's no ++. |
items.forEach((item) => ...) | items.each do (item) ... end. |
items.each { |x| ... }, do |x| ... end | items.each do (x) ... end. No pipes, no braces. |
| The block's last line is its value | return value. In blocks, return ends just the block. |
each_with_index | do (item, index) |
select, detect, any?, all? | filter, find, any, all |
items.map(&:name), reduce, inject | Not available. sum, min, max, average and tally take a block; for anything else, use each and a var. |
sort_by, sort { |a, b| ... } | sort do (x) ... end, the block giving what to sort by. |
take(n), drop(n) | limit(n), skip(n). |
group_by, uniq | group do (x) ... end, the block giving each item's key; unique(). |
next (skip to the next pass) | continue. |
break value, next value | Plain break and continue, only in while and each. |
lambda x: x * 2 | Blocks, given to the built-in methods that take them: items.map do (x): Int ... end. |
def each(&block), block.call(x), keeping a block | A block isn't a value. A method says it takes one after its signature, def each_item() do (Int), and runs it with yield(x). It can't keep it. |
Strings and conversions
Strings use double quotes, and #{} is the way to put a value into one, so text never joins a number by accident. Conversions are written out: String(n), Int(x), Float(s). See strings and conversions.
Not this
"age: " + 36 giving "age: 36"
Write this
"age: #{36}". Joining a string and a number with + is an error.
| Habit | In Hematite |
|---|---|
'single quoted' strings | Double quotes only. Interpolation always works. |
f"Hi {name}" | "Hi #{name}". |
`Hi ${name}` | "Hi #{name}". |
"Hi $name" | "Hi #{name}". |
Heredocs, %q(), ''' | A text block: """ ends its line, the closing """ starts one. |
"#{nil}" is "" | Error. Only values that can't be nil go into a string. |
"a" * 3, "a" < "b" | Not available yet. |
len(items), len(text) | items.length, text.length. |
items.empty?, text.empty? | items.length == 0 |
text.strip, text.include?("x"), items.include?(x) | text.trim(), text.contains("x"), items.contains(x) |
text[2..5], text.gsub("a", "b"), text.index("x"), text.chars | text.slice(from: 2, to: 6), text.replace("a", by: "b"), text.index_of("x"), text.characters |
text.start_with?("x"), text.end_with?("x") | text.contains("x", at: Placement.start), at: Placement.finish |
n.to_s, x.to_i, s.to_f | String(n), Int(x), Float(s). Int(2.5) is an error: round first. |
Arrays and hashes
An array or a hash holds one type, is read and written through its methods, and is a value: assigning it or passing it makes an independent copy. Reading past the end of an array is an error, never a quiet nil; a hash's get says it may be nil in its type, and the checker makes sure you check. See arrays and hashes.
Not this
ages["Ada"], ages["Bob"] = 40
Write this
ages.get("Ada"), ages.set("Bob", to: 40)
| Habit | In Hematite |
|---|---|
[1, "two", nil] (mixed arrays) | One type per array. nil only in arrays typed like [Int?]. |
items[10] past the end gives nil | Error. |
items[-1] is the last element | Error. Use items[items.length - 1]. |
items << 4 | items.push(4) |
items.size, items.count | items.length |
b = a shares the array; changing b changes a | b is an independent copy. |
| A method can change an array passed to it | Parameters can't be changed. Copy into a var, then return the result. |
{"Ada" => 36}, {name: "Ada"} (symbol keys) | {"Ada": 36}. Keys are written-out strings or numbers. There are no symbols. |
{name: 36} meaning the key "name" | Error: write {"name": 36}. |
dict["key"] | ages.get("key"), ages.set("key", to: 1). |
ages.fetch, ages.key?, ages.delete | ages.get (gives nil when missing), ages.has, ages.remove |
ages.fetch("Bob", 0) | ages.get("Bob", fallback: 0) |
Hash.new(0) (default values) | Not available. Check with .has first. |
Classes and objects
A class declares its fields at the top, with types, and its methods inside it. Objects are values, like arrays and hashes. Classes share fields and methods through traits: there is no inheritance, on purpose. See classes and records and traits.
Not this
@balance
Write this
self.balance
| Habit | In Hematite |
|---|---|
Fields appear when first assigned in initialize | Fields are declared at the top of the class, with types. |
def initialize(...) | new Account(owner: "Ada") sets the readable and writable fields by name. |
Account.new(...) | new Account(...) |
attr_reader, attr_accessor | readable var, writable var |
Calling an own method bare: total | self.total() (or self.total without arguments) |
impl blocks | Methods are written inside the class. |
b = a shares the object | b is an independent copy. |
| Borrowing and lifetimes | None to think about: arrays, hashes and objects are values, copied when assigned. |
Inheritance (class Admin < User) | Not available, on purpose. Share fields and methods with a trait. |
include Trackable (modules, concerns) | A trait: trait Trackable ... end, and with Trackable at the top of the class. |
| Interfaces, abstract classes | A trait: trait Name, and with Name in the class. |
data class, record types | record: fields only, always readable, never changed. |
Failures
A method that can fail says so in its return type, with !, and fails with return failure("..."). Every call to it handles the failure: try passes it on, rescue deals with it there. Nothing passes through a method without it saying so. See failures.
Not this
throw and try/catch
Write this
: T!, return failure("..."), and try or rescue at every call.
| Habit | In Hematite |
|---|---|
raise and rescue: any call may raise, and exceptions pass silently through methods that don't mention them | A method that can fail says so (: Int!), and every call to it handles the failure with try or rescue. There is no raise and no begin. |
try: / except / raise | A method that can fail says so (: Int!) and fails with return failure("..."); callers use try or rescue. |
| Exceptions, checked or not | : T! and return failure("..."); every call handles it. |
if err != nil { return err } | try call() passes a failure on. |
Result<T, E> and ? | T! and try. |
async/await, promises | Not needed: a call that waits, like File.read(path, as: String) or Input.line(), gives its result when it's there. |
JSON.parse(text) | try JSON.decode(text, as: Type): the result is checked against the type. |
Files
A file shares only what it marks with export, and only with the files that import it. Case means nothing here either: a capital letter doesn't export a name, export does. See imports and exports.
Not this
require runs a file, and its definitions are then visible everywhere.
Write this
import brings in only what a file exports, only into the file that imports it, and runs none of its code.