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 is the same as , unless is an atom, in which case must be a module qualifier for . 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 , where is an atom, is the same as the call . For example, the expression .name returns the name of , and the expression .arity returns the arity of if 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.
| 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:
- copy_term() = : This function copies into . If is an attributed variable, then will not contain any of the attributes.
- copy_term_shallow() = : This function copies the skeleton of into . If is a variable or an atomic value, then it returns a complete copy of , the same as copy_term(); if is a list, then it returns a cons [] where both the car and the cdr are free variables; otherwise, it is the same as new_struct(name(), arity()).
- hash_code() = : This function returns the hash code of . If is a variable, then the returned hash code is always 0.
- to_codes() = : This function returns a list of character codes of .
- to_fstring(, ) = : This function converts the arguments in the parameter into a string, according to the format string , and returns the string. The number of arguments in cannot exceed 10. Format characters are described in Chapter 11.
- to_string() = : This function returns a string representation of .
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:
- var(): This predicate is true if is a free variable.
- nonvar(): This predicate is true if is not 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:
- attr_var(): This predicate is true if is an attributed variable.
- bool_dvar(): This predicate is true if is an attributed domain variable whose lower bound is 0 and whose upper bound is 1.
- dvar(): This predicate is true if is an attributed domain variable.
- dvar_or_int(): This predicate is true if is an attributed domain variable or an integer.
- get_attr(, ) = : This function returns the of the pair that is attached to . It throws an error if has no attribute named .
- get_attr(, , ) = : This function returns of the pair that is attached to . It returns if does not have the attribute named .
- put_attr(, ): This is the same as put_attr(, , not_a_value).
- put_attr(, , ): This predicate attaches the pair to , where is a non-variable term, and is any term.
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:
- ascii_alpha(): This predicate is true if is an atom and the atom consists of a single letter.
- ascii_alpha_digit(): This predicate is true if is an atom and the atom consists of a single letter or digit.
- ascii_digit(): This predicate is true if is an atom and the atom consists of a single digit.
- ascii_lowercase(): This predicate is true if is an atom and the atom consists of a single lowercase letter.
- ascii_uppercase(): This predicate is true if is an atom and the atom consists of a single uppercase letter.
- atom(): This predicate is true if is an atom.
- atom_chars() = : This function returns a string that contains the characters of the atom . It throws an error if is not an atom.
- atom_codes() = : This function returns the list of codes of the characters of the atom . It throws an error if is not an atom.
- atomic(): This predicate is true if is an atom or a number.
- char(): This predicate is true if is an atom and the atom consists of a single character.
- chr() = : This function returns the UTF-8 character of the code point .
- digit(): This predicate is true if is an atom and the atom consists of a single digit.
- len() = : This function returns the number of characters in . Note that this function is overloaded in such a way that the argument can also be an array, a list, or a structure.
- length() = : This function is the same as len().
- lowercase(): This predicate checks if is a lowercase character atom.
- ord()
= :
This function returns the code point of the UTF-8 character .
It throws an error if is not a single-character atom. - to_atom() = : This function converts to an atom.
- uppercase(): This predicate checks if is an uppercase character atom.
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.
| ** | power |
| + | same as |
| - | sign reversal |
| ~ | bitwise complement |
| * | multiplication |
| / | division |
| // | integer division, truncated |
| /> | integer division (ceiling( / )) |
| /< | integer division (floor( / )) |
| div | integer division, floored |
| mod | modulo, same as - floor( div ) * |
| rem | remainder ( - ( // ) * ) |
| + | addition |
| - | subtraction |
| 1 | right shift |
| left shift | |
| /' | bitwise and |
| ^ | bitwise xor |
| ' / | bitwise or |
| .. .. | A range (list) of numbers with a step |
| .. | A range (list) of numbers with step 1 |
| =:= | pretty much (numerically) equal |
In addition to the numeric operators, the basic module also provides the following built-ins for numbers:
- between(, , ) (nondet): If is bound to a number, then this predicate determines whether is between and . Otherwise, if is unbound, then this predicate nondeterministically selects from the numbers that are between and with step 1. It is the same as member(, [ : in ..]), but it does not create the list.
-
between(, , , ) (nondet): This predicate nondeterministically selects from the numbers that are between and with , where , , and must be numbers. It is the same as
member(, [ : in ....])
but it does not create the list.
- bigint(): This predicate is true if is a big integer.
- float(): This predicate is true if is a real number.
- int(): This predicate is true if is an integer.
- integer(): The same as int().
- max(, ) = : This function returns the maximum of and , where and are terms.
- maxint_small() = : This function returns the maximum integer that is represented in one word. All integers that are greater than this integer are represented as big integers.
- min(, ) = : This function returns the minimum of and , where and are terms.
- minint_small() = : This function returns the minimum integer that is represented in one word. All integers that are smaller than this integer are represented as big integers.
- number(): This predicate is true if is a number.
- number_chars() = : This function returns a list of characters of . This function is the same as to_fstring("%d", ) if is an integer, and is similar to to_fstring("%g", ) if is a real number.
- number_codes() = : This function returns a list of codes of the characters of . It is the same as number_chars().to_codes().
- real(): This predicate is the same as float().
- to_binary_string() = : This function returns the binary representation of the integer as a string.
- to_float() = :2 This function is the same as *1.0 if is a number, and the same as 1.0*parse_term() if is a string.
- to_hex_string() = : This function returns the hexadecimal representation of the integer as a string.
- to_int() = :3 This function is the same as truncate() in the math module if is a number, the same as ord()-ord(’0’) if is a digit character, and the same as to_int(parse_term()) if is a string.
- to_integer() = : This function is the same as to_int().
- to_number() = : This function is the same as if is a number, the same as ord()-ord(’0’) if is a digit character, and the same as to_number(parse_term()) if is a string.
- to_oct_string() = : This function returns the octal representation of the integer as a string.
- to_radix_string(, ) = : This function returns the string representing integer in base , where must be greater than 1 and less than 37. The call to_oct_string() is the same as to_radix_string(, 8).
- to_real() = : This function is the same as to_float().
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 be a variable that references a compound value, and let be an integer expression that evaluates to an integer or an integer range. The index notation [], where is a variable referencing a compound value, is a special function that returns the th component of if is an integer or a slice of components if is a range in the form of , counting from the beginning.4 Subscripts begin at , meaning that [] is the first component of . 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() is true if is a compound term.
3.4.1 Lists
A list takes the form [,,], where each () is a term. Let be a list. The expression .length, which is the same as length(), returns the length of . 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 [|] can occur in a pattern or in an expression. When it occurs in a pattern, it matches any list in which matches the car and matches the cdr. When it occurs in an expression, it builds a list from and . The notation [,,,|] is a shorthand for [|[|[|]]. 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).
- ++ = : This function returns the concatenated list of and .
- append(, , ) (nondet): This predicate is true if appending to can create . This predicate may backtrack if is not a complete list.5
-
append(, , , ) (nondet): This predicate is defined as:
append(W, X, Y, Z) => append(W, X, WX), append(WX, Y, Z). - avg() = : This function returns the average of all the elements in . This function throws an exception if is not a list or any of the elements is not a number.
- delete(, ) = : This function deletes the first occurrence of from , returning the result in . The built-in !=/2 is used to test if two terms are different. No variables in or will be bound after this function call.
- delete_all(, ) = : This function deletes all occurrences of from , returning the result in . The built-in !=/2 is used to test if two terms are different.
- first() = : This function returns the first element of .
- flatten() = : This function flattens a list of nested lists into a list. For example, flatten([[1],[2,[3]]]) returns [1,2,3].
- head() = : This function returns the head of the list . For example, head([1,2,3]) returns 1.
- insert(,
,
) =
: This function
inserts into
at the index
, returning the result
in . After insertion,
the original is
not changed, and
is the same as
.slice(1, -1)++[|.slice(,.length)]. - insert_all(,
,
) =
: This function inserts
all of the elements in
into at the index
, returning the result
in . After insertion,
the original is
not changed, and
is the same as
.slice(1, -1)++++.slice(, .length). - insert_ordered(, ) = : This function inserts into the ordered list , such that the resulting list remains sorted.
- insert_ordered_down(, ) = : This function inserts into the ordered list , such that the resulting list remains in descending order.
- last() = : This function returns the last element of .
- len() = : This function returns the number of elements in . Note that this function is overloaded in such a way that the argument can also be an atom, an array, or a structure.
- length() = : This function is the same as len().
- list(): This predicate is true if is a list.
- max() = : This function returns the maximum value that is in , where is a list of terms.
- membchk(, ): This predicate is true if is an element of .
- member(, ) (nondet): This predicate is true if is an element of . When is a variable, this predicate may backtrack, instantiating to different elements of .
- min() = : This function returns the minimum value that is in , where is a list or an array of terms.
- new_list() = : This function creates a new list that has free variables.
- new_list(, ) = : This function creates a new list that has elements initialized to .
- nth(, , ) (nondet): This predicate is true when is the element at index in . Counting starts at 1. When is a variable, this predicate may backtrack, instantiating to a different integer between 1 and len().
- prod() = : This function returns the product of all of the values in .
- remove_dups() = : This function removes all duplicate values from , retaining only the first occurrence of each value. The result is returned in . Note that an algorithm is used in the implementation. For long lists, sort_remove_dups is faster than this function.
- reverse() = : This function reverses the order of the elements in , returning the result in .
- select(, , ) (nondet): This predicate nondeterministically selects an element from , and binds to the list after is removed. On backtracking, it selects the next element.
- slice(, , ) = : This function returns the sliced list of from index through index . must not be less than 1. It is the same as the index notation [..].
-
slice(, ) = : This function is the same as the following.
slice(, , .length)
- sort() = : This function sorts the elements of in ascending order, returning the result in .
-
sort(, ) = : This function sorts the elements of by the key index in ascending order, returning the result in . The elements of must be compound values and must be a positive integer that does not exceed the length of any of the elements of . In particular, if an element is a list, then must be either 1 or 2. This function is defined as follows:
sort(List, KeyIndex) = SList => List1 = [(A, E) : E in List, arg(KeyIndex,E,A)], List2 = sort(List1), SList = [E : (_,E) in List2]. -
sort_remove_dups() = : This function is the same as the following, but is faster.
sort().remove_dups()
-
sort_remove_dups(, ) = : This function is the same as the following, but is faster.
sort(, ).remove_dups()
- sort_down() = : This function sorts the elements of in descending order, returning the result in .
- sort_down(, ) = : This function sorts the elements of by the key index in descending order, returning the result in .
-
sort_down_remove_dups() = : This function is the same as the following, but is faster.
sort_down().remove_dups()
-
sort_down_remove_dups(, ) = : This function is the same as the following, but is faster.
sort_down(, ).remove_dups()
- sorted(): This predicate checks if is sorted in ascending order.
- sorted_down(): This predicate checks if is sorted in descending order.
- sum() = : This function returns the sum of all of the values in .
- tail() = : This function returns the tail of the list . For example, the call tail([1,2,3]) returns [2,3].
- to_array() = : This function converts the list to an array. The elements of the array are in the same order as the elements of the list.
- zip(, , , ) = : This function makes a list of array tuples. The th tuple in the list takes the form {}, where is the th element in . In the current implementation, can be 2, 3, or 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:
- string(): This predicate is true if is a string.
- to_lowercase() = : This function converts all uppercase alphabetic characters into lowercase characters, returning the result in .
- to_uppercase() = : This function converts all lowercase alphabetic characters into uppercase characters, returning the result in .
3.4.3 Structures
A structure takes the form $(, , ), where is an atom, and 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:
- =.. : The name and the arguments of comprise the list . This predicate extracts the name and arguments of when is instantiated, and constructs from the list when is instantiated.
- arg(, , ): The th argument of the term is . This predicate is equivalent to: = , = , except when is 0 or is a list. When is 0, the call fails. When is a list, only two indices, namely 1 and 2, are acceptable. For = 1, is unified with the car of the list, and for = 2, is unified with the cdr of the list.
- arity() = : This function returns the arity of , which must be a structure.
- functor(, , ): The principal functor of the term has the name and the arity . This predicate extracts the functor of when is instantiated, and constructs a term of the given functor when is a variable.
- len() = : This function is the same as arity().
- name() = : This function returns the name of .
- new_struct(, ) = : This function creates a structure that has the name . If is an integer, , then the structure has free variable arguments. Otherwise, if is a list, then the structure contains the elements in the list.
- struct(): This predicate is true if is a structure.
- to_list() = : This function returns a list of the components of the structure .
3.4.4 Arrays
An array takes the form {,,}, which is a special structure with the name ’{}’ and arity . Note that, unlike a list, an array always has its length stored in memory, so the function length() 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 is an integer.
In addition to the built-ins for structures, the following built-ins are provided for arrays:
- array(): This predicate is true if is an array.
- new_array(, , ) = : This function creates an n-dimensional array, where each is an integer expression that specifies the size of a dimension. In the current implementation, cannot exceed 10.
The following built-ins, which are originally provided for lists (see 3.4.1), are overloaded for arrays:
- ++ =
- avg() =
- first() =
- last() =
- len() =
- length() =
- max() =
- min() =
- nth(, , ) (nondet)
- prod() =
- reverse() =
- slice(, ) =
- slice(, , ) =
- sort() =
- sort(, ) =
- sort_down() =
- sort_down(, ) =
- sort_down_remove_dups() =
- sort_down_remove_dups(, ) =
- sort_remove_dups() =
- sort_remove_dups(, ) =
- sorted()
- sorted_down()
- sum() =
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:
- clear(): This predicate clears the map . It throws an error if is not a map.
- del(, ): This predicate deletes from the pair that has the key . It throws an error if is not a map. It does nothing if does not contain a pair with .
- get(, ) = : This function returns of the pair in . It throws an error if does not contain the key .
- get(,
,
)
= :
This function returns
of the pair
in . It returns if does not contain . - has_key(, ): This predicate is true if contains a pair with .
- keys() = : This function returns the list of keys of the pairs in .
- map(): This predicate is true if is a map.
- map_to_list() = : This function returns a list of pairs that constitute .
- new_map() = : This function creates an empty map.
- new_map() = : This function creates a map with an initial capacity or an initial list of pairs.
- new_map(, ) = : This function creates a map with initial capacity and initial list of pairs , where each pair has the form .
- put(, , ): This predicate attaches the pair to , where is a non-variable term, and is any term.
- put(, ): This predicate is the same as put(, , not_a_value).
- size() = : This function returns the number of pairs in .
- values() = : This function returns the list of values of the pairs in .
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(, ) tests if is in . In addition to the built-ins on maps, the following built-ins are provided for sets:
- new_set() = : This function creates an empty set.
- new_set() = : This function creates a set with an initial capacity or an initial list of keys.
- new_set(, ) = : This function creates a set with the initial capacity and the initial list of keys .
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.
- heap_is_empty(): This predicate is true if is empty.
- heap_pop() = : This function removes the root element from the heap, and returns the element. As the function updates the heap, it is not pure. The update will be undone when execution backtracks over the call.
- heap_push(, ): This predicate pushes into in a way that maintains the heap property. The update to will be undone when execution backtracks over the call.
- heap_size() = : This function returns the size of .
- heap_to_list() = : This function returns a list of the elements in .
- heap_top() = : This function returns the element at the root of the heap. If is a min-heap, then the element is guaranteed to be the minimum, and if is a max-heap, then the element is guaranteed to be the maximum.
- new_max_heap() = : This function creates a max-heap. If is an integer, then it indicates the capacity. Otherwise, if is a list, then the max-heap contains the elements in the list in an order that maintains the heap property.
- new_min_heap() = : This function creates a min-heap. If is an integer, then it indicates the capacity. Otherwise, if is a list, then the min-heap contains the elements in the list in an order that maintains the heap property.
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 == is true if term and term 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 !== is the same as not == . 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 = is true if term and term are already identical, or if they can be made identical by instantiating the variables in the terms. The built-in != is true if term and term are not unifiable. The predicate bind_vars(, ) binds all of the variables in to .
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 and , where is younger than , are unified, is bound to , but ’s attributes are not copied to . 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 =:= is true if term and term are pretty much the same numerical value. This means that and must both be numbers after evaluation. Whereas the test == fails if one number is an integer and one number is a real number, the test =:= may succeed if the absolute difference between and is less than 0.00000001. Consider the following examples.
Example
Picat> 1 == 1.0
no
Picat> 1 =:= 1.0
yes
In the first query, is an integer, while is a real number, so the equality test fails. However, the second query, which is a numerical equality test, succeeds.
- is : If is a variable, then the call binds the variable to the result of , which must be a number after evaluation. If is a non-variable expression, then the call is equivalent to =:= .
- =' = : The expression is not numerically equal to .
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.
- @< : The term precedes the term in the standard order. For example, a @< b succeeds.
- @=< : The term either precedes, or is identical to, the term in the standard order. For example, a @=< b succeeds.
- @<= : This is the same as @=< .
- @> : The term follows the term in the standard order.
- @>= : The term either follows, or is identical to, the term in the standard order.
3.6 Expressions
Expressions are made from variables, values, operators, and function calls. Expressions differ from terms in the following ways:
- An expression can contain dot notations, such as math.pi.
- An expression can contain index notations, such as X[I].
- An expression can contain ranges, such as 1..2..100.
- An expression can contain list comprehensions, such as [X : X in 1..100].
- An expression can contain array comprehensions, such as {X : X in 1..100}.
A conditional expression, which takes the form cond(, , ), is a special kind of function call that returns the value of if the condition is true and the value of if 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.
- apply(, , , ) = : is an atom or a structure. This function calls the function that is named by with the arguments that are specified in , together with extra arguments , …, . This function returns the value that returns. The apply invocation can be written in short as (, , ).
- call(, , , ): is an atom or a structure. This predicate calls the predicate that is named by with the arguments that are specified in , together with extra arguments , …, . The call invocation can be written in short as (, , ).
- call_cleanup(, ): This predicate is the same as call(), except that is called when succeeds deterministically (i.e., with no remaining choice point), when fails, or when raises an exception.
- catch(, , ): This predicate is the same as , except when an exception that unifies with is raised during the execution of . When such an exception is raised, all of the bindings that have been performed on variables in will be undone, and will be executed to handle the exception.
- count_all() = : This function returns the number of all possible instances of call() that are true. For example, count_all(member(X, [1,2,3])) returns 3.
- findall(, ) = : This function returns a list of all possible instances of call() that are true in the form of . Note that is assumed to be a term without function calls, and that is assumed to be a predicate call whose arguments can contain function calls. Also note that, like a loop, findall forms a name scope. For example, in findall(f(X), p(X, g(Y))), f(X) is a term even though it is not preceded with $; g(Y) is a function call; the variables X and Y are assumed to be local to findall if they do not occur before in the outer scope.
- find_all(, ) = : This function is the same as the above function.
-
fold(, , ) = : This function combines the elements of into a single result by repeatedly applying to each element from left to right and to the updated accumulator. It is defined as follows:
fold(F, Acc, []) = Acc. fold(F, Acc, [H|T]) = fold(F, F(H, Acc), T). - freeze(, ): This predicate delays the evaluation of until becomes a non-variable term.
- map(, ) = : This function applies a given function to every element of a given list and returns a list of the results. One of the arguments is a function, and the other is a list. The order of the arguments is not important.
-
= [,,] and = [,,].
This function applies the function to every pair of elements by calling apply(, , ), and returns a list of the results.
- maxof(, ): This predicate finds a satisfiable instance of , such that has the maximum value. Here, is used as a generator, and is an expression to be maximized. For every satisfiable instance of , must be a ground expression. For maxof, search is restarted with a new bound each time that a better answer is found.
- maxof(,
,
): This predicate is
the same as maxof(,
), except that call() is executed each time that an answer is found. - maxof_inc(,
): This predicate is
the same as maxof(,
), except that search continues rather than being restarted each time that a better solution is found. - maxof_inc(,
,
):
This predicate is the same as
maxof_inc/2, except that call() is executed each time that an answer is found. - minof(, ): This predicate finds a satisfiable instance of , such that has the minimum value.
- minof(,
,
): This predicate is
the same as minof(,
), except that call() is executed each time that an answer is found. - minof_inc(,
): This predicate is
the same as minof(,
), except that search continues rather than being restarted each time that a better solution is found. - minof_inc(,
,
):
This predicate is the same as
minof_inc/2, except that call() is executed each time that an answer is found. - reduce(, ) = : If is a list that contains only one element, this function returns the element. If contains at least two elements, then the first two elements and are replaced with apply(, , ). This step is repeatedly applied to the list until the list contains a single element, which is the final value to be returned. The order of the arguments is not important, meaning that the first argument can be a list and the second one can be a function.
- reduce(,
,
) =
:
This function is the same as
reduce(, []).
3.8 Other Built-ins in the basic Module
- acyclic_term(): This predicate is true if is acyclic, meaning that does not contain itself.
- and_to_list() = : This function converts in the form (, , ) into a list in the form [,,].
- compare_terms(,
)
= :
This function compares
and
. If , then this function returns . If , then this function returns . Otherwise, , and this function returns . - different_terms(, ): This constraint ensures that and are different. This constraint is suspended when the arguments are not sufficiently instantiated.
- get_global_map() = : This function returns the global map.
- get_global_map() = : This function returns the global map with the identifier , which must be a ground term.
- get_heap_map() = : This function returns the default heap map.
- get_heap_map() = : This function returns the heap map with the identifier , which must be a ground term.
- get_table_map() = : This function returns the default table map. The table map is stored in the table area and both keys and values are hash-consed (i.e., common sub-terms are shared).
- get_table_map() = : This function returns the table map with the identifier , which must be a ground term.
- ground(): This predicate is true if is ground. A ground term does not contain any variables.
- list_to_and() = : This function converts in the form [,,] into a term in the form (, , ).
- number_vars(): This predicate numbers the variables in by using the integers starting from 0. Different variables receive different numberings, and the occurrences of the same variable all receive the same numbering.
- number_vars(, ) = : This function numbers the variables in by using the integers starting from . is the next integer that is available after is numbered.
- parse_radix_string(, ) = : This function parses as an integer in base and returns the decimal integer, where must be greater than 1 and less than 37. For example, parse_radix_string("101", 2) returns 5, which is the same as parse_term("0b101").
- parse_term(, , ): This predicate uses the Picat parser to extract a term from . is a map that contains pairs each of which has the form =.
- parse_term() = : This function converts to a term.
- second() = : This function returns the second argument of the compound term .
- subsumes(, ): This predicate is true if subsumes .
- variant(, ): This predicate is true if is a variant of . and cannot share variables.
- vars() = : This function returns a list of variables that occur in .
1As in the C language, oversized right shift, meaning that is negative or larger than ’s bit length, is undefined.
2Here, is a number or a string.
3Here, is a number, a character, or a string.
4 must reference a list or an array if 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.