• Rel
• REL PRIMER

# Rel Primer: Advanced Syntax

Introducing more advanced Rel syntax.

## Introduction

This document assumes that you are familiar with Basic Rel Syntax, and introduces more advanced features of the Rel language.

## Grounded and Ungrounded Variables

You can begin by considering what relations Rel can be expected to compute.

A variable is grounded when it can be instantiated to a specific, finite set of values. For example, in the expression x: range(1, 100, 1, x), using the built-in range relation, the variable x is instantiated to the 100 different values 1, 2, 3, ..., 100 to produce the relation. Similarly, when you write x : minimum(1, 2, x), the variable x is bound to 1.

By contrast, if you write x: minimum(1, x, 1), there are infinitely many values of x for which minimum(1,x,1) is true; and if you write x, y: range(1, y, 1, x), there are infinitely many possible values for both x and y. These variables are said to be ungrounded.

When the RAI Server encounters one of these cases, you will see an error stating that the definition “contains ungrounded variable(s); hence, the rule cannot be evaluated.”

In general, if you write range(x, y, z, result), you should expect to know the values of x, y, z, and say that those values grounded the value of result.

## @inline Definitions

You can still declare and use definitions that are not expected to be fully computed, by using the @inline keyword. For example:

// query

@inline
def mymax[x, y] = maximum[abs[x], abs[y]]
def output = mymax[-10, -20]

Here, mymax is not intended to be computed directly — you would not expect to enumerate all the tuples that satisfy it. If it were not labeled as @inline, the Rel compiler would attempt to compute mymax and complain that x and y are ungrounded.

You can add the @inline annotation to any relation. If you have a large derived relation but are only interested in querying it for particular values, it can be best to inline it, so that the system does not compute all values in that relation. Similarly, if the rest of your code only needs a few values.

## Relations as Arguments

Relations in Rel are first-order, meaning they do not take relations as values. But we can use @inline to define syntactically “higher-order” relations, which can take a relation as one of their arguments.

For example:

// query

@inline
def maxmin[Relation] = (max[Relation], min[Relation])
def output = maxmin[ {1; 2; 3; 4; 5} ]


Here we used max and min from the stdlib, which take relations as their argument as well.

In an @inline definition, variable names that correspond to relations must start with an uppercase letter, as is the case with Relation above.

This does not contradict the first-order nature of the language: when the @inline def is expanded, the result is first-order again. Readers with experience with programming languages can think of @inline definitions as macros that are expanded at compile-time. They are not directly evaluated themselves, keeping things first-order.

argmax is another stdlib utility that takes a relation R as argument, returning the rows in R that have the largest value. For example:

// query

def output = argmax[{("a", 2, 3); ("b", 1, 6) ; ("c", 10, 6)}]


We can use argmax on the sample data from the aggregation Primer section to find the highest-paid players for a particular team. Here are the plays_for and salary relations:

plays_for

salary

// query

def output = argmax[name, s : plays_for(name, "BFC") and salary(name, s)]

It is easy to generalize this query to get the highest-paid player for each team that participates in the plays_for relation:

// query

def output = team: argmax[name, s : plays_for(name, team) and salary(name, s)]

### Example

Here’s an example of how @inline functions can give the code a higher-order flavor. The x... syntax is explained in the Varargs section below.

// query

@inline
def plusone[R][x...] = R[x...] + 1
def foo = (1, 3); (4, 5); (5, 6, 10)
def bar = plusone[foo]
def output = bar

## Multiple Arities

Mathematically speaking, an individual relation has a fixed arity. However, Rel lets us define relations with different arities but the same name. This is sometimes (informally) known as overloading, where we can treat a set of relations as a single one. For example:

// query

def foo = 1, 2
def foo = 1, 4, 6
def output = foo

foo

output

The built-in predicate arity can be used to check the arity, or arities, of a relation R. For example:

// query

def output = arity[{6 ; (7, 8) }]


Thus, if count[arity[R]] = 1, then R is not overloaded by arity.

## Varargs

To write more general code that works for many different arities, Rel provides a varargs mechanism, where x... matches zero or more variables. For example, the stdlib defines first and last as:

@inline
def first[R](x) = ∃(y... : R(x, y...))

@inline
def last[R](y) = ∃(x... : R(x..., y))

These could also be defined as:

@inline
def first[R](x) = R(x, y...) from y...
@inline
def last[R](y) = R(x..., y) from x...

As another example, in Basic Syntax we discussed how R[S] only works for unary relations S. We can write a more general version as follows:

// query

@inline
def prefix_restrict[PREFIX, R] = R[x...] from x... in PREFIX

def foo = (1, 2, 3); (4, 5, 6); (7, 8, 9)
def r = {(1, 2); (4, 5)}
def output = prefix_restrict[r, foo]

(prefix_restrict is closely related to the stdlib’s prefix_join, aka <:, discussed below.)

When using varargs, keep in mind that the system needs to compute the arity of any requested predicates. For an overloaded relation, this should be a finite number of arities. For example, the following query succeeds, and foo(1) is true:

// query

@inline def foo(vs..., 1) = true
def output:yes = foo(1)

When computing output, the system sees that foo has arity 1, and thus vs... is an empty list of variables.

However, the following query fails; while foo(1) constrains foo to have exactly arity 1, foo only constrains it to be non-zero, so foo could have any one of an infinite number of arities:

@inline def foo(vs..., 1) = true
def output:yes = foo

### A Word About Arities

In general, we prefer relations with small arities, and working with normalized data, which keeps the arities small and helps with performance, readability, and correctness. Therefore, while varargs are very useful to write general utilities (see the Standard Library for examples), the arity of individual relations should not be too high. (Note how even wide CSV tables are ingested as a set of ternary relations, for example.)

## Multiple Types

Relations can also be overloaded by type, meaning that they can contain tuples with different types. You can think of each combination of types as a separate relation. A Rel expression can also refer to a combination of different arities and types. For example:

// query

def myrel = 1; 2.0
def myrel = ("a", "b") ; (3, 4)
def output = myrel

## Specialization: RelNames (:name)

Related to overloading by type, relations can be specialized, which separates them into different relations depending on the particular values they take.

This is always the case for RelNames, which are values starting with a colon (:), such as :a and :b below: For example:

// query

def foo[:a] = 1
def foo[:b] = 2
def output = foo

When using the RAI Console query editor on your browser, you will notice that the “physical” output view shows the specialized relations for :a and for :b separately.

Imported CSV relations are specialized by the column name, which is a symbol, so each column becomes a separate relation.

### RelNames and Base Relation Updates

We sometimes use the symbol :relname to refer to the relation relname, particularly when updating stored relations (using insert[:relname]=... and delete[:relname]=.... See the concept guide on Updating Data: Working with Base Relations.

### RelNames and Modules

The correspondence between RelName symbols and specialized relations also shows up in modules, where module:foo is the same as module[:foo]. See the Rel Modules Concept Guide for more details.

## Recursion

Rel supports recursive definition, provided the recursion is well-founded (has a base case) and the relations computed are finite.

// query

def fib = 0
def fib = 1
def fib[x in range[2,10,1]] = fib[x-1] + fib[x-2]
def output = fib

See the Recursion Concept Guide for more details.

🔎

For readers familiar with Logic Programming and Datalog, we note that currently all relations are computed in a bottom-up fashion, rather than top-down/on-demand, although this will change in the future. Combining negation and recursion is supported, as long as the resulting program is stratified (meaning, roughly, no cyclic recursive definitions with a negation in the loop, as in def p = not p).

## Multiple Rules Add Up

As mentioned in the Basic Syntax section, the definitions for any given relation are combined.

This is the case even if the definitions are in separate installed models or libraries. It can be useful to extend existing relations for new types or arities. This applies even to recursive definitions, where we can add new base cases or new recursive definitions to an existing one.

// install

def rec = 10
def rec[x] = rec[x-1] + 5, range(1, 4, 1, x)

The following definition adds a new base case:

// query

def rec = 200
def output = rec

The order of the rules does not matter — and they can be separated by other rules, or even be installed separately.

🔎

Multiple rules can always be combined into a single rule that does a big disjunction between the different cases. Separating the cases into different rules is usually more natural and readable.

Another interesting feature of this example is that while the first two rules for rec were installed, the extra base case was part of a query, which enables it only for the effects of that query itself. This means that if we ask for rec again, we get only the values from the rules that were originally installed:

// query

def output = rec

## Point-Free Syntax

Rel’s syntax supports point-free notation, where we can omit argument variables when their omission does not lead to ambiguity. For example, instead of writing:

def mydomain(x) = range(1, 7, 1, x)

we can write:

def mydomain = range[1, 7, 1]

Again, conjunctions correspond to , and disjunctions to ;. For example:

def myrel(x, y) = r1(x) and r2(y)

can be expressed point-free as:

def myrel = r1, r2

In both cases, we get the cross-product of r1 and r2.

To see how ; corresponds to or:

def myrel(x, y) = r1(x, y) or r2(x, y)

is equivalent to:

def myrel = r1 ; r2

As another example, instead of:

// query

def a = {(1, 2)}
def b = {(1, 2) ; (3, 4)}
def myrel(x,y) = a(x,y) and b(x,y)
def output = myrel

we can use intersect from the stdlib and write:

def myrel = intersect[a, b]

We can even use point-free recursive definitions, such as this one, for the transitive closure of the binary relation r (see below for an explanation of the composition operator . ):

// query

def r = {(1,2); (2,3); (3,4); (2,5)}
def tcr = r
def tcr = tcr.r // see section below for the meaning of "."
def output = tcr
🔎

Compared to the “point-wise” alternative, point-free Rel code can be easier to read and faster to write, since it needs fewer variables. It can sometimes be harder to debug, particularly regarding arities, which will not be obvious from reading the code.

Note that writing def myrel = a and b will give an arity error if a and b do not have arity 0, which and expects. Similarly for or, not, and implies.

## Relational Equality: equal vs. =

In Rel, = means equality between individual (scalar) values. (That is, when = is used in a formula; the ”=” used in def myrel = ...  has a special status as a reserved symbol). For example, 3 = 2 + 1 is true, and writing x = y supposes that x and y are individual values.

To test equality between relations, equal should be used:

// query

def output = if equal({1; 2; 3} , {3; 2; 1; 2}) then "yes" else "no" end

Since Rel distributes scalar operations over relation values, using = for relations can give confusing results. For example:

// query

// do not use = to check equality of relations!
def output:wrong = if {1} = {1; 2; 3} then "equal" else "not equal" end
// use equals for relations:
def output:right = if equal({1}, {1; 2; 3}) then "equal" else "not equal" end

Technical footnote: If R1 and R2 are relations, then R1 = R2 if and only if their intersection is non-empty.

Use = to compare individual values, and equal to compare relations.

## Useful Relational Operators

The Rel Standard Library defines many useful relational operations.

This section describes some of the most commonly used relational operations.

### Composition (.)

Relational composition, indicated by a dot (.), is a shortcut for joining the last element of a relation with the first element of another — usually a foreign key:

// query

def order_products = {(12, 3213) ; (10, 3213) ; (7, 9832)}
def product_names = {(3213, "laptop"); (9832, "iphone"); (45353, "TV")}
def output = order_products.product_names

As another example, if parent(x, y) holds when x is a parent of y, then x : x.parent.parent is the “grandparent” relation:

// query

def parent = {("bill", "alice") ; ("alice" , "bob") ;
("alice" , "mary") ; ("jane", "john")}
def output = "bill".parent.parent

### Prefix and Suffix Joins (<: and :>)

Prefix join, written as prefix_join[R, S] or R <: S, generalizes [] to get the elements of a relation S that have a prefix in R. Using varargs notation, R <: S contains the tuples (x..., y...) in S where (x...) is in R. For example:

// query

def r = {(1, 2); (2, 5)}
def s = {(1, 2, 3); (1, 5, 7); (1, 2, 8); (2, 5, 9)}
def output = r <: s
// query

def json = parse_json["""{"a": {"b": 1, "c": 2}, "d": 3}"""]
def output = :a <: json

Suffix join, written as suffix_join[S, R] or S :> R is similar, but matches suffixes. R :> S contains the tuples (x..., y...) in R where (y...) is in S:

// query

def r = {(1, 2, 3); (1, 5, 7); (1, 2, 8); (2, 5, 9)}
def s = {(2, 3); (5, 9)}
def output = r :> s
// query

@inline def even(x) = (x%2=0)
def json = parse_json["""[ {"a": 1, "b": 2}, {"a": 3, "b": 4, "c": 6} ]"""]
def output = json :> even

(Here, the prefix ([], n) indicates a JSON list, with n as the index. For details on how JSON is represented in Rel, see the JSON topic guide.)

### Left and Right Override (<++ and ++>)

The (left) override operator is usually applied to relations of tuples (k..., v) with a functional dependency from the initial (key) arguments k... to the last argument v (the value). It lets us merge two such relations, giving precedence to one over the other.

left_override[R, S], also written as R <++ S, contains all the tuples (x..., v) of R, plus all the tuples (x1..., v1) of S where x1..., is not in R. Often, S specifies default values for keys that are missing in R.

As a mnemonic, when we read R <++ S we can imagine S injecting new values into R, but only when those keys are missing (so R is overriding S).

// query

def base  = ("a", 2) ; ("b", 4)
def defaultvalues = ("a", 10) ; ("c", 20)
def combined = (base <++ defaultvalues)
def output = combined

A common use case for override is making explicit default values, using a constant relation for the default. We can write count[R] <++ 0 if we want the count of an empty relation to be 0 rather than empty. As another example, a counter can be defined using a base relation as follows:

// update

def delete[:counter] = counter
def insert[:counter] = (counter + 1) <++ 0

(Note that without the delete, the consecutive values will accumulate in counter, rather than replace each other. See the Concept Guide on Updating Data for details.)

Here is an example of how we can add defaults for a domain, with a definition using in:

// query

def base = ("a", 10)
def mydomain = ("a" ; "b" ; "c")
def filled[x in mydomain] = base[x] <++ 0
def output = filled

Rel also provides ++> (right_override, which swaps the order of the arguments.

As a special case, count[R] <++ 0 gives us a count of zero for empty sets (see Aggregating over the Empty Set).

## Types

Rel provides unary relations for testing the type of primitive values. These tests include String, Number, Int, and Float, which take one argument, and counterparts for fixed-width types, such as Floating. Example: Floating[32, float[32, 3.0]] is true.

See the Data Types Reference for details on all of the primitive types.

Types are particularly useful for enforcing schemas as integrity constraints. For example,

ic { subset(myrel, (Int, Float, String) ) }

will make sure that myrel has the given type signature (Int x Float x String).

This works for both base relations and derived relations. If myrel is a base relation, then any insert that tries to add something of the wrong type will fail. If myrel is a derived relation, then any database update that would cause it to be populated by the wrong type will also fail.

## Summary

This article has covered more advanced features of Rel, including higher-order definitions, overloading by arity and types, varargs, specialization and point-free syntax.