Chapter 3

Data Types, Operators, and Built-ins

On this page

Picat is a dynamically typed language, in which type checking occurs at runtime. A variable gets a type once it is bound to a value. In Picat, variables and values are terms. A value can be primitive or compound. A primitive value can be an integer, a real number, or an atom. A compound value can be a list or a structure. Strings, arrays, maps, sets, and heaps are special compound values. This chapter describes the data types and the built-ins for each data type that are provided by the basic module.

Many of the built-ins are given as operators. Table 3.1 shows all of the operators that are provided by Picat. Unless the table specifies otherwise, the operators are left-associative. The as-pattern operator (@) and the operators for composing goals, including not, once, conjunction (,  and &&), and disjunction (; and ||), will be described in Chapter 4 on Predicates and Functions. The constraint operators (the ones that begin with #) will be described in Chapter 13 on Constraints. In Picat, no new operators can be defined, and none of the existing operators can be redefined.

The dot operator (.) is used in OOP notations for calling predicates and functions. It is also used to qualify calls with a module name. The notation A1 .f(A2 , … ,Ak) is the same as f(A1 , A2 ,…,Ak), unless A1 is an atom, in which case A1 must be a module qualifier for f. If an atom needs to be passed as the first argument to a function or a predicate, then this notation cannot be used. The notation A.f, where f is an atom, is the same as the call A.f(). For example, the expression S.name returns the name of S, and the expression S.arity returns the arity of S if S is a structure. Note that the dot operator is left-associative. For example, the expression X.f().g() is the same as g(f(X)). Also note that functions in dot notation are always evaluated eagerly, and therefore should not be used in term constructs or constraint expressions.

Table 3.1: Operators in Picat

Precedence Operators
Highest ., @
** (right-associative)
unary +, unary -, ~
*, /, //, /<, />, div, mod, rem
binary +, binary -
>>, <<
/'
^
' /
..
++ (right-associative)
is, =, !=, :=, ==, !==, =:=, =' =, <, =<, <=, >, >=, ::, in, notin, =..
#=, #!=, #<, #=<, #<=, #>, #>=, @<, @=<, @<=, @>, @>=
#~
#/'
#^
#' /
#=> (right-associative)
#<=>
not, once, ' +
,  (right-associative), && (right-associative)
Lowest ; (right-associative), || (right-associative)

The following functions are provided for all terms:

Other built-ins on terms are given in Sections 3.5 and 3.8.

3.1 Variables

Variables in Picat, like variables in mathematics, are value holders. Unlike variables in imperative languages, Picat variables are not symbolic addresses of memory locations. A variable is said to be free if it does not hold any value. A variable is instantiated when it is bound to a value. Picat variables are single-assignment, which means that after a variable is instantiated to a value, the variable will have the same identity as the value. After execution backtracks over a point where a binding took place, the value that was assigned to a variable will be dropped, and the variable will be turned back into a free variable.

A variable name is an identifier that begins with a capital letter or an underscore. For example, the following are valid variable names:

    X1   _   _ab

The name _ is used for anonymous variables. In a program, different occurrences of _ are treated as different variables. So the test  _ == _ is always false.

The following two built-ins are provided to test whether a term is a free variable:

An attributed variable is a variable that has a map of attribute-value pairs attached to it. The following built-ins are provided for attributed variables:

3.2 Atoms

An atom is a symbolic constant. An atom name can either be quoted or unquoted. An unquoted name is an identifier that begins with a lowercase letter, followed by an optional string of letters, digits, and underscores. A quoted name is a single-quoted sequence of arbitrary characters. A character can be represented as a single-character atom. For example, the following are valid atom names:

    x   x_1   '_'   '\\'   'a\'b\n'   '_ab'   '$%'

An atom name cannot span more than one line. An atom name cannot contain more than 1000 characters. The backslash character ’' ’ is used as the escape character. So, the name ’a' ’b' n’ contains four characters: a, ’, b, and ' n.

The following built-ins are provided for atoms:

3.3 Numbers

A number can be an integer or a real number. An integer can be a decimal numeral, a binary numeral, an octal numeral, or a hexadecimal numeral. In a numeral, digits can be separated by underscores, but underscore separators are ignored by the tokenizer. For example, the following are valid integers:

  12_345 a decimal numeral
  0b100 4 in binary notation
  0o73 59 in octal notation
  0xf7 247 in hexadecimal notation

A real number consists of an integer part, a decimal fraction preceded by a decimal point, and an optional exponent. For example, the following are valid real numbers.

    12.345   0.123   12.0e-10   0.12E10

Table 3.2 gives the meaning of each of the numeric operators in Picat, from the operator with the highest precedence (**) to the one with the lowest precedence (=:=). Except for the power operator **, which is right-associative, all of the arithmetic operators are left-associative.

Table 3.2: Arithmetic Operators

X ** Y power
+X same as X
-X sign reversal
~X bitwise complement
X * Y multiplication
X / Y division
X // Y integer division, truncated
X /> Y integer division (ceiling(X / Y ))
X /< Y integer division (floor(X / Y ))
X div Y integer division, floored
X mod Y modulo, same as X - floor(X div Y ) * Y
X rem Y remainder (X - (X // Y ) * Y )
X + Y addition
X - Y subtraction
X > > Y 1 right shift
X < < Y left shift
X /' Y bitwise and
X ^ Y bitwise xor
X ' / Y bitwise or
From .. Step .. To A range (list) of numbers with a step
From .. To A range (list) of numbers with step 1
X =:= Y pretty much (numerically) equal

In addition to the numeric operators, the basic module also provides the following built-ins for numbers:

The math module provides more numeric functions. See Appendix 15.5.

3.4 Compound Terms

A compound term can be a list or a structure. Components of compound terms can be accessed with subscripts. Let X be a variable that references a compound value, and let I be an integer expression that evaluates to an integer or an integer range. The index notation X[I], where X is a variable referencing a compound value, is a special function that returns the Ith component of X if I is an integer or a slice of components if I is a range in the form of l..u, counting from the beginning.4 Subscripts begin at 1, meaning that X[1] is the first component of X. An index notation can take multiple subscripts. For example, the expression X[1, 2] is the same as T[2], where T is a temporary variable that references the component that is returned by X[1]. The predicate compound(Term) is true if Term is a compound term.

3.4.1 Lists

A list takes the form [t1,…,tn], where each ti (1 ≤ i ≤ n) is a term. Let L be a list. The expression L.length, which is the same as length(L), returns the length of L. Note that a list is represented internally as a singly linked list. Also note that the length of a list is not stored in memory; instead, it is recomputed each time that the function length is called.

The symbol ’|’ is not an operator, but a separator that separates the first element (so-called car) from the rest of the list (so-called cdr). The cons notation [H|T] can occur in a pattern or in an expression. When it occurs in a pattern, it matches any list in which H matches the car and T matches the cdr. When it occurs in an expression, it builds a list from H and T. The notation [A1 ,A2,…,An|T] is a shorthand for [A1|[A2|…[An|T]…]. So [a,b,c] is the same as [a|[b|[c|[]]]].

The basic module provides the following built-ins on lists, most of which are overloaded for strings (3.4.2) and arrays (see 3.4.4).

3.4.2 Strings

A string is represented as a list of single-character atoms. For example, the string "hello" is the same as the list [h,e,l,l,o]. In addition to the built-ins on lists, the following built-ins are provided for strings:

3.4.3 Structures

A structure takes the form $s(t1, …, tn ), where s is an atom, and n is called the arity of the structure. The dollar symbol is used to distinguish a structure from a function call. The functor of a structure comprises the name and the arity of the structure.

The following types of structures can never denote functions, meaning that they do not need to be preceded by a $ symbol.

  Goals: (a, b),  (a;b),  not a,  X = Y,  X != 100,  X > 1
  Constraints: X+Y #= 100,  X #!= 1
  Arrays: {2,3,4},  {P1,P2,P3}

Picat disallows creation of the following types of structures:

  Dot notations: math.pi,  my_module.f(a)
  Index notations: X[1]+2 X[Y[I]]
  Assignments: X := Y+Z,  X := X+1
  Ranges: 1..10,  1..2..10
  List comprehensions: [X : X in 1..5]
  Array comprehensions: {X : X in 1..5}
  If: if (X > Y) Z = X else Z = Y end
  Loops: foreach (X in L) writeln(X) end
  Higher-order: F(X,Y)

The compiler will report syntax errors when it encounters assignments, if statements, or loops within term constructors, and treat dot notations, index notations, ranges, list & array comprehensions, and higher-order calls as function calls in term constructors.

The following built-ins are provided for structures:

3.4.4 Arrays

An array takes the form {t1,…,tn}, which is a special structure with the name ’{}’ and arity n. Note that, unlike a list, an array always has its length stored in memory, so the function length(Array) always takes constant time. Also note that Picat supports constant-time access of array elements, so the index notation A[I] takes constant time when I is an integer.

In addition to the built-ins for structures, the following built-ins are provided for arrays:

The following built-ins, which are originally provided for lists (see 3.4.1), are overloaded for arrays:

Note that many of the overloaded built-ins for arrays are not implemented efficiently, but are provided for convenience. For example, sort(Array) is implemented as follows:

    sort(Array) = Array.to_list().sort().to_array().

3.4.5 Maps

A map is a hash-table that is represented as a structure that contains a set of key-value pairs. The functor of the structure that is used for a map is not important. An implementation may ban access to the name and the arity of the structure of a map. Maps must be created with the built-in function new_map, unless they are prebuilt (see Section 1.11). In addition to the built-ins for structures, the following built-ins are provided for maps:

3.4.6 Sets

A set is a map where every key is associated with the atom not_a_value. All of the built-ins for maps can be applied to sets. For example, the built-in predicate has_key(Set, Elm) tests if Elm is in Set. In addition to the built-ins on maps, the following built-ins are provided for sets:

3.4.7 Heaps

A heap6 is a complete binary tree represented as an array. A heap can be a min-heap or a max-heap. In a min-heap, the value at the root of each subtree is the minimum among all the values in the subtree. In a max-heap, the value at the root of each subtree is the maximum among all the values in the subtree.

Example

main =>
    L = [1,3,2,4,5,3,6],
    H = new_min_heap(L),
    N = H.heap_size(),
    S = [H.heap_pop() : _ in 1..N],
    println(S).

3.5 Equality Testing, Unification, and Term Comparison

The equality test T1 == T2 is true if term T1 and term T2 are identical. Two variables are identical if they are aliases. Two primitive values are identical if they have the same type and the same internal representation. Two lists are identical if the cars are identical and the cdrs are identical. Two structures are identical if their functors are the same and their components are pairwise identical. The inequality test T1 !== T2 is the same as not T1 == T2 . Note that two terms can be identical even if they are stored in different memory locations. Also note that it takes linear time in the worst case to test whether two terms are identical.

The unification T1 = T2 is true if term T1 and term T2 are already identical, or if they can be made identical by instantiating the variables in the terms. The built-in T1 != T2 is true if term T1 and term T2 are not unifiable. The predicate bind_vars(Term, V al) binds all of the variables in Term to V al.

Example

    Picat> X = 1
    X = 1
    Picat> $f(a, b) = $f(a, b)
    yes
    Picat> [H|T] = [a,b,c]
    H = a
    T = [b,c]
    Picat> $f(X, b) = $f(a, Y)
    X = a
    Y = b
    Picat> bind_vars({X,Y,Z}, a)
    Picat> X = $f(X)

The last query illustrates the occurs-check problem. When binding X to f(X), Picat does not check if X occurs in f(X) for the sake of efficiency. This unification creates a cyclic term, which can never be printed.

When a unification’s operands contain attributed variables, the implementation is more complex. When a plain variable is unified with an attributed variable, the plain variable is bound to the attributed variable. When two attributed variables, say Y and O, where Y is younger than O, are unified, Y is bound to O, but Y ’s attributes are not copied to O. Since garbage collection does not preserve the seniority of terms, the result of the unification of two attributed variables is normally unpredictable.

3.5.1 Numerical Equality

The numerical equality test T1 =:= T2 is true if term T1 and term T2 are pretty much the same numerical value. This means that T1 and T2 must both be numbers after evaluation. Whereas the test T1 == T2 fails if one number is an integer and one number is a real number, the test T1 =:= T2 may succeed if the absolute difference between T1 and T2 is less than 0.00000001. Consider the following examples.

Example

    
Picat> 1 == 1.0
no

Picat> 1 =:= 1.0
yes

In the first query, 1 is an integer, while 1.0 is a real number, so the equality test fails. However, the second query, which is a numerical equality test, succeeds.

3.5.2 Ordering of Terms

Picat orders terms in the following way:

  var  < number   < atom   < structure and array  < list and string

Variables are ordered by their addresses. Note that the ordering of variables may change after garbage collection. Numbers are ordered by their numerical values. Atoms are ordered lexicographically. Structures are first ordered lexicographically by their names; if their names are the same, then they are ordered by their components. Arrays are ordered as structures with the special name ’{}’. Lists and strings are ordered by their elements.

3.6 Expressions

Expressions are made from variables, values, operators, and function calls. Expressions differ from terms in the following ways:

A conditional expression, which takes the form cond(Cond, Exp1 , Exp2 ), is a special kind of function call that returns the value of Exp1 if the condition Cond is true and the value of Exp2 if Cond is false.

Note that, except for conditional expressions in which the conditions are made of predicates, no expressions can contain predicates. A predicate is true or false, but never returns any value.

3.7 Higher-order Predicates and Functions

A predicate or function is said to be higher-order if it takes calls as arguments. The basic module has the following higher-order predicates and functions.

3.8 Other Built-ins in the basic Module

1As in the C language, oversized right shift, meaning that Y is negative or larger than X’s bit length, is undefined.

2Here, NS is a number or a string.

3Here, NCS is a number, a character, or a string.

4X must reference a list or an array if I is a range.

5A list is complete if it is empty, or if its tail is complete. For example, [a,b,c]and [X,Y,Z]are complete, but [a,b|T] is not complete if Tis a variable.

6Note that a heap, as a data structure, is different from the heap area, in which data, including heap maps, are stored.