Operators#

Meta: lead with the precedence table — it's what people scroll back to. Per-operator notes can be terse if the table is precise.

The examples on this page are live: they share one Dang environment, so later snippets use earlier definitions. Each result is computed and baked in by the docs build — edit a snippet and hit Run ▶ to replay the page in your browser. Blocks that show an error are supposed to fail: the build verifies the failure the same way it verifies the results.

Precedence (low → high)#

Precedence follows the DefaultExpr → … → MultiplicativeExpr → Term chain in pkg/dang/dang.peg.

level operators assoc
1 ?? right
2 or left
3 and left
4 ==, != left
5 <, <=, >, >= left
6 +, - left
7 *, /, % left
8 ! (prefix), - (unary), & (prefix) —
9 ! (postfix), ., .{{ }}, .{ }, [], () left

?? binds loosest of all, which matters when you mix it with arithmetic. Here the second line reads as scores[0] ?? (0 + 100):

let scores = [10, null, 30]

[scores[0] ?? 0 + 100, (scores[0] ?? 0) + 100]
=> [10, 110]

:: (cast / type hint) is not in this chain. In the grammar it's a sibling of ?? and binds only a bare Term on its left, so (a + b) :: T! needs the parens (see Types and nullability):

1 + 2 :: Int!
Parse error: syntax error: unexpected '+ 2'

Arithmetic#

+ - * / % work on Int and Float. / on two Ints drops the remainder, and % gives it:

[7 / 2, 7 % 2]
=> [3, 1]

Mixing an Int with a Float gives a Float. For %, the remainder takes the sign of the left operand:

[7 / 2.0, 7.5 % 2, -7.5 % 2]
=> [3.5, 1.5, -1.5]

Dividing by zero raises a runtime error, and so does % 0:

10 / 0
Runtime error: division by zero

+ also joins strings and lists. The other operators are numeric only:

"con" + "cat"
=> "concat"
[1, 2] + [3]
=> [1, 2, 3]

Operands outside an operator's domain are a type error, caught before the script runs:

"a" * "b"
Type error: operator multiplication is not defined for type String!
1 + "foo"
Type error: operator addition is not defined between types Int! and String!

Operands must be non-null. Operators don't pass null through the way field access does, so a nullable operand is a type error:

scores[1] + 1
Type error: operator addition is not defined for nullable type Int: supply a default with ??, assert it with !, or bind it to a local with let and check that for null

Hand the operator a non-null value with ! (raises if the value is null), with ??, or with a null check (see Flow-sensitive narrowing):

[scores[0]! + 1, (scores[1] ?? 0) + 1]
=> [11, 1]

The result is non-null. List + keeps the left operand's type, so the right operand's elements must fit the left's element type. [scores[0]] + [1] is fine, but this is not:

[1] + [scores[0]]
Type error: cannot use [Int]! as [Int!]!

In a generic function, the arithmetic operators take values of a type variable bounded by Numeric ([a: Numeric], see Type parameters, Ordered and Numeric), with only the numeric meaning of +.

Comparison#

< <= > >= compare values of any Ordered type: numbers (Int and Float mix), strings (by their bytes, so "B" < "a"), booleans (false first), enum values (in declaration order), custom scalars, and lists and {{ }} records of those, element by element. It's the same order .sort uses, and a function can ask for it with a type parameter bounded by Ordered (see Type parameters, Ordered and Numeric):

[1 < 2.5, "apple" < "banana", false < true, [1, 2] < [1, 3]]
=> [true, true, true, true]

Both operands must be the same type and non-null, as for arithmetic:

"a" < 1
Type error: operator less_than is not defined between types String! and Int!

== and != only compare values that could be equal: the same type (nullability aside), Int with Float, a type with its interface, a union with its members, and anything with null. Nullable operands are fine, and both return Boolean!:

[1 == 1.0, scores[1] == null, [1, 2] == [1, 2]]
=> [true, true, true]

Comparing unrelated types is an error:

1 == "1"
Type error: cannot compare Int! with String!: they are unrelated types

A string literal compared with an enum or a custom scalar converts to it, as it does for arguments and case patterns (see Enums and scalars). Color.GREEN is still the clearer way to write an enum value:

enum Color { RED GREEN }

let light = Color.GREEN
let userId: ID! = "User:1"

[light == "GREEN", light != Color.RED, userId == "User:1"]
=> [true, true, true]

An enum literal must name one of the enum's values:

light == "PURPLE"
Type error: "PURPLE" is not a value of Color; expected one of RED, GREEN

A String held in a variable doesn't convert at all. Cast it:

let wanted = "GREEN"
light == wanted
Type error: cannot compare Color! with String!: they are unrelated types; compare with a Color value, like Color.RED, or cast the string: (wanted :: Color!)
light == (wanted :: Color!)
=> true

Records ({{…}} literals and .{{…}} selections) compare by value: equal when every field is equal. Records with different fields can't be compared:

[{{a: 1}} == {{a: 1}}, {{a: 1}} == {{a: 2}}]
=> [true, false]
{{a: 1}} == {{b: 1}}
Type error: cannot compare {a: Int!}! with {b: Int!}!: they are unrelated types

Objects of a named type compare by type, then by their stored fields. Computed members (field: T { … }) are behavior, not stored state, so they're ignored:

type Rabbit {
  name: String!
  shout: String! { name.toUpper }
}

[Rabbit("Bun") == Rabbit("Bun"), Rabbit("Bun") == Rabbit("Hop")]
=> [true, false]

Two different types, or a named object and a record, can't be compared:

type Hare { name: String! }
Rabbit("Bun") == Hare("Bun")
Type error: cannot compare Rabbit! with Hare!: they are unrelated types

GraphQL objects compare by identity. A GraphQL object's identity is the query that produced it, so two queries for the same user are not equal. To ask whether two objects are the same server entity, compare an identifying field such as id. This uses the bundled Demo schema (see GraphQL interop):

import Demo

[primaryUser == user(id: "User:1"), primaryUser.id == user(id: "User:1").id]
→ query Query {user(id:"User:1"){id __typename}} → query Query {primaryUser{id}} → query Query {user(id:"User:1"){id}}
=> [false, true]

Logical#

and and or short-circuit, so the right side runs only when it's needed. Both return Boolean!, and ! negates a Boolean!. They're keywords: there is no && or ||.

[false and 1 / 0 == 0, !true]
=> [false, false]

There's no truthiness: every operand must be a Boolean!:

1 and true
Type error: logical 'and' left operand must be Boolean!, got Int!

Default (??)#

a ?? b is a unless a is null, in which case it's b. The result has the type of the right operand, so a non-null fallback gives a non-null result (T ?? T! is T!, T ?? T is T). It's right-associative: a ?? b ?? c reads as a ?? (b ?? c).

let nickname = null :: String
let username = "ada" :: String

nickname ?? username ?? "anonymous"
=> "ada"

Non-null assertion (postfix !)#

expr! asserts that a nullable value isn't null. It narrows the type from T to T!, and raises at runtime if the value is null. Use it when [flow-sensitive narrowing]Flow-sensitive narrowing can't prove what you know, such as a field or call result. Prefer narrowing when you can.

username!.toUpper
=> "ADA"
nickname!
Runtime error: non-null assertion failed: value is null

It sticks to the term right before it: a.b! is (a.b)!, and a! + b is (a!) + b. Write it with no space before the !; a != b and a!=b are still inequality.

Compound assignment#

x += y is short for x = x + y, and works for numbers, strings, and lists:

let total = 1
total += 2

let words = ["a"]
words += ["b"]

[total, words.length]
=> [3, 2]

The target must be a variable, field, or argument, and since += reads it, it must be non-null:

let visits: Int = 0
visits += 1
Type error: compound assignment needs a non-null target, got Int: declare it non-null (with a default), or write `x = (x ?? default) + value`

Declare it non-null (with a default), or write visits = (visits ?? 0) + 1. Assigning through ! (visits! += 1) is rejected too.

= is plain reassignment, not an operator on the precedence chain.

Cast / type hint: ::#

Unary#

[-(1 + 2), -1 + 2]
=> [-3, 1]

Meta: it's worth a paragraph on why and/or are keywords (readability) rather than &&/||. Same for != vs <>.