update docs

This commit is contained in:
Vítor Santos Costa 2014-09-11 14:06:57 -05:00
parent 19c247accd
commit 3009987985
150 changed files with 13817 additions and 1515 deletions

View File

@ -491,6 +491,31 @@
*************************************************************************/
/**
@file absmi.c
@page Efficiency Efficiency Considerations
We next discuss several issues on trying to make Prolog programs run
fast in YAP. We assume two different programming styles:
+ Execution of <em>deterministic</em> programs often
boils down to a recursive loop of the form:
~~~~~
loop(Env) :-
do_something(Env,NewEnv),
loop(NewEnv).
~~~~~
*/
#define IN_ABSMI_C 1
#define HAS_CACHE_REGS 1

View File

@ -853,8 +853,33 @@ void
Yap_InitAnalystPreds(void)
{
Yap_InitCPred("wam_profiler_reset_op_counters", 0, p_reset_op_counters, SafePredFlag |SyncPredFlag);
/** @pred wam_profiler_reset_op_counters
Reinitialize all counters.
*/
Yap_InitCPred("wam_profiler_show_op_counters", 1, p_show_op_counters, SafePredFlag|SyncPredFlag);
/** @pred wam_profiler_show_op_counters(+ _A_)
Display the current value for the counters, using label _A_. The
label must be an atom.
*/
Yap_InitCPred("wam_profiler_show_ops_by_group", 1, p_show_ops_by_group, SafePredFlag |SyncPredFlag);
/** @pred wam_profiler_show_ops_by_group(+ _A_)
Display the current value for the counters, organized by groups, using
label _A_. The label must be an atom.
*/
Yap_InitCPred("wam_profiler_show_sequences", 1, p_show_sequences, SafePredFlag |SyncPredFlag);
}

View File

@ -15,6 +15,92 @@
* *
*************************************************************************/
/** @defgroup YAPArrays Arrays
@ingroup YAPBuiltins
@{
The YAP system includes experimental support for arrays. The
support is enabled with the option `YAP_ARRAYS`.
There are two very distinct forms of arrays in YAP. The
<em>dynamic arrays</em> are a different way to access compound terms
created during the execution. Like any other terms, any bindings to
these terms and eventually the terms themselves will be destroyed during
backtracking. Our goal in supporting dynamic arrays is twofold. First,
they provide an alternative to the standard arg/3
built-in. Second, because dynamic arrays may have name that are globally
visible, a dynamic array can be visible from any point in the
program. In more detail, the clause
~~~~~
g(X) :- array_element(a,2,X).
~~~~~
will succeed as long as the programmer has used the built-in <tt>array/2</tt>
to create an array term with at least 3 elements in the current
environment, and the array was associated with the name `a`. The
element `X` is a Prolog term, so one can bind it and any such
bindings will be undone when backtracking. Note that dynamic arrays do
not have a type: each element may be any Prolog term.
The <em>static arrays</em> are an extension of the database. They provide
a compact way for manipulating data-structures formed by characters,
integers, or floats imperatively. They can also be used to provide
two-way communication between YAP and external programs through
shared memory.
In order to efficiently manage space elements in a static array must
have a type. Currently, elements of static arrays in YAP should
have one of the following predefined types:
+ `byte`: an 8-bit signed character.
+ `unsigned_byte`: an 8-bit unsigned character.
+ `int`: Prolog integers. Size would be the natural size for
the machine's architecture.
+ `float`: Prolog floating point number. Size would be equivalent
to a double in `C`.
+ `atom`: a Prolog atom.
+ `dbref`: an internal database reference.
+ `term`: a generic Prolog term. Note that this will term will
not be stored in the array itself, but instead will be stored in the
Prolog internal database.
Arrays may be <em>named</em> or <em>anonymous</em>. Most arrays will be
<em>named</em>, that is associated with an atom that will be used to find
the array. Anonymous arrays do not have a name, and they are only of
interest if the `TERM_EXTENSIONS` compilation flag is enabled. In
this case, the unification and parser are extended to replace
occurrences of Prolog terms of the form `X[I]` by run-time calls to
array_element/3, so that one can use array references instead of
extra calls to arg/3. As an example:
~~~~~
g(X,Y,Z,I,J) :- X[I] is Y[J]+Z[I].
~~~~~
should give the same results as:
~~~~~
G(X,Y,Z,I,J) :-
array_element(X,I,E1),
array_element(Y,J,E2),
array_element(Z,I,E3),
E1 is E2+E3.
~~~~~
Note that the only limitation on array size are the stack size for
dynamic arrays; and, the heap size for static (not memory mapped)
arrays. Memory mapped arrays are limited by available space in the file
system and in the virtual memory space.
The following predicates manipulate arrays:
*/
#include "Yap.h"
#include "clause.h"
#include "eval.h"
@ -2440,19 +2526,142 @@ Yap_InitArrayPreds( void )
Yap_InitCPred("$array_references", 3, p_array_references, SafePredFlag);
Yap_InitCPred("$array_arg", 3, p_array_arg, SafePredFlag);
Yap_InitCPred("static_array", 3, p_create_static_array, SafePredFlag|SyncPredFlag);
/** @pred static_array(+ _Name_, + _Size_, + _Type_)
Create a new static array with name _Name_. Note that the _Name_
must be an atom (named array). The _Size_ must evaluate to an
integer. The _Type_ must be bound to one of types mentioned
previously.
*/
Yap_InitCPred("resize_static_array", 3, p_resize_static_array, SafePredFlag|SyncPredFlag);
/** @pred resize_static_array(+ _Name_, - _OldSize_, + _NewSize_)
Expand or reduce a static array, The _Size_ must evaluate to an
integer. The _Name_ must be an atom (named array). The _Type_
must be bound to one of `int`, `dbref`, `float` or
`atom`.
Note that if the array is a mmapped array the size of the mmapped file
will be actually adjusted to correspond to the size of the array.
*/
Yap_InitCPred("mmapped_array", 4, p_create_mmapped_array, SafePredFlag|SyncPredFlag);
/** @pred mmapped_array(+ _Name_, + _Size_, + _Type_, + _File_)
Similar to static_array/3, but the array is memory mapped to file
_File_. This means that the array is initialized from the file, and
that any changes to the array will also be stored in the file.
This built-in is only available in operating systems that support the
system call `mmap`. Moreover, mmapped arrays do not store generic
terms (type `term`).
*/
Yap_InitCPred("update_array", 3, p_assign_static, SafePredFlag);
/** @pred update_array(+ _Name_, + _Index_, ? _Value_)
Attribute value _Value_ to _Name_[ _Index_]. Type
restrictions must be respected for static arrays. This operation is
available for dynamic arrays if `MULTI_ASSIGNMENT_VARIABLES` is
enabled (true by default). Backtracking undoes _update_array/3_ for
dynamic arrays, but not for static arrays.
Note that update_array/3 actually uses `setarg/3` to update
elements of dynamic arrays, and `setarg/3` spends an extra cell for
every update. For intensive operations we suggest it may be less
expensive to unify each element of the array with a mutable terms and
to use the operations on mutable terms.
*/
Yap_InitCPred("dynamic_update_array", 3, p_assign_dynamic, SafePredFlag);
Yap_InitCPred("add_to_array_element", 4, p_add_to_array_element, SafePredFlag);
/** @pred add_to_array_element(+ _Name_, + _Index_, + _Number_, ? _NewValue_)
Add _Number_ _Name_[ _Index_] and unify _NewValue_ with
the incremented value. Observe that _Name_[ _Index_] must be an
number. If _Name_ is a static array the type of the array must be
`int` or `float`. If the type of the array is `int` you
only may add integers, if it is `float` you may add integers or
floats. If _Name_ corresponds to a dynamic array the array element
must have been previously bound to a number and `Number` can be
any kind of number.
The `add_to_array_element/3` built-in actually uses
`setarg/3` to update elements of dynamic arrays. For intensive
operations we suggest it may be less expensive to unify each element
of the array with a mutable terms and to use the operations on mutable
terms.
*/
Yap_InitCPred("array_element", 3, p_access_array, 0);
/** @pred array_element(+ _Name_, + _Index_, ? _Element_)
Unify _Element_ with _Name_[ _Index_]. It works for both
static and dynamic arrays, but it is read-only for static arrays, while
it can be used to unify with an element of a dynamic array.
*/
Yap_InitCPred("reset_static_array", 1, p_clear_static_array, SafePredFlag);
/** @pred reset_static_array(+ _Name_)
Reset static array with name _Name_ to its initial value.
*/
Yap_InitCPred("close_static_array", 1, p_close_static_array, SafePredFlag);
/** @pred close_static_array(+ _Name_)
Close an existing static array of name _Name_. The _Name_ must
be an atom (named array). Space for the array will be recovered and
further accesses to the array will return an error.
*/
Yap_InitCPred("$sync_mmapped_arrays", 0, p_sync_mmapped_arrays, SafePredFlag);
Yap_InitCPred("$compile_array_refs", 0, p_compile_array_refs, SafePredFlag);
Yap_InitCPred("$array_refs_compiled", 0, p_array_refs_compiled, SafePredFlag);
Yap_InitCPred("$static_array_properties", 3, p_static_array_properties, SafePredFlag);
Yap_InitCPred("static_array_to_term", 2, p_static_array_to_term, 0L);
/** @pred static_array_to_term(? _Name_, ? _Term_)
Convert a static array with name
_Name_ to a compound term of name _Name_.
This built-in will silently fail if the there is no static array with
that name.
*/
Yap_InitCPred("static_array_location", 2, p_static_array_location, 0L);
/** @pred static_array_location(+ _Name_, - _Ptr_)
Give the location for a static array with name
_Name_.
*/
}
/**
@}
*/

View File

@ -18,6 +18,17 @@
static char SccsId[] = "%W% %G%";
#endif
/** @defgroup Predicates_on_Atoms Predicates on Atoms
@ingroup YAPBuiltins
@{
The following predicates are used to manipulate atoms:
*/
#define HAS_CACHE_REGS 1
/*
* This file includes the definition of a miscellania of standard operations
@ -2077,6 +2088,23 @@ Yap_InitBackAtoms(void)
Yap_InitCPredBack("atom_concat", 3, 2, init_atom_concat3, cont_atom_concat3, 0);
Yap_InitCPredBack("string_concat", 3, 2, init_string_concat3, cont_string_concat3, 0);
Yap_InitCPredBack("sub_atom", 5, 5, init_sub_atom, cont_sub_atomic, 0);
/** @pred sub_atom(+ _A_,? _Bef_, ? _Size_, ? _After_, ? _At_out_) is iso
True when _A_ and _At_out_ are atoms such that the name of
_At_out_ has size _Size_ and is a sub-string of the name of
_A_, such that _Bef_ is the number of characters before and
_After_ the number of characters afterwards.
Note that _A_ must always be known, but _At_out_ can be unbound when
calling this built-in. If all the arguments for sub_atom/5 but _A_
are unbound, the built-in will backtrack through all possible
sub-strings of _A_.
*/
Yap_InitCPredBack("sub_string", 5, 5, init_sub_string, cont_sub_atomic, 0);
Yap_InitCPredBack("string_code", 3, 1, init_string_code3, cont_string_code3, 0);
@ -2086,28 +2114,126 @@ void
Yap_InitAtomPreds(void)
{
Yap_InitCPred("name", 2, p_name, 0);
/** @pred name( _A_, _L_)
The predicate holds when at least one of the arguments is ground
(otherwise, an error message will be displayed). The argument _A_ will
be unified with an atomic symbol and _L_ with the list of the ASCII
codes for the characters of the external representation of _A_.
~~~~~{.prolog}
name(yap,L).
~~~~~
will return:
~~~~~{.prolog}
L = [121,97,112].
~~~~~
and
~~~~~{.prolog}
name(3,L).
~~~~~
will return:
~~~~~{.prolog}
L = [51].
~~~~~
*/
Yap_InitCPred("string_to_atom", 2, p_string_to_atom, 0);
Yap_InitCPred("atom_string", 2, p_atom_string, 0);
Yap_InitCPred("string_to_atomic", 2, p_string_to_atomic, 0);
Yap_InitCPred("string_to_list", 2, p_string_to_list, 0);
Yap_InitCPred("char_code", 2, p_char_code, SafePredFlag);
/** @pred char_code(? _A_,? _I_) is iso
The built-in succeeds with _A_ bound to character represented as an
atom, and _I_ bound to the character code represented as an
integer. At least, one of either _A_ or _I_ must be bound before
the call.
*/
Yap_InitCPred("atom_chars", 2, p_atom_chars, 0);
/** @pred atom_chars(? _A_,? _L_) is iso
The predicate holds when at least one of the arguments is ground
(otherwise, an error message will be displayed). The argument _A_ must
be unifiable with an atom, and the argument _L_ with the list of the
characters of _A_.
*/
Yap_InitCPred("atom_codes", 2, p_atom_codes, 0);
Yap_InitCPred("string_codes", 2, p_string_codes, 0);
Yap_InitCPred("string_chars", 2, p_string_chars, 0);
Yap_InitCPred("atom_length", 2, p_atom_length, SafePredFlag);
/** @pred atom_length(+ _A_,? _I_) is iso
The predicate holds when the first argument is an atom, and the second
unifies with the number of characters forming that atom.
*/
Yap_InitCPred("atomic_length", 2, p_atomic_length, SafePredFlag);
Yap_InitCPred("string_length", 2, p_string_length, SafePredFlag);
Yap_InitCPred("$atom_split", 4, p_atom_split, SafePredFlag);
Yap_InitCPred("number_chars", 2, p_number_chars, 0);
/** @pred number_chars(? _I_,? _L_) is iso
The predicate holds when at least one of the arguments is ground
(otherwise, an error message will be displayed). The argument _I_ must
be unifiable with a number, and the argument _L_ with the list of the
characters of the external representation of _I_.
*/
Yap_InitCPred("number_atom", 2, p_number_atom, 0);
/** @pred number_atom(? _I_,? _L_)
The predicate holds when at least one of the arguments is ground
(otherwise, an error message will be displayed). The argument _I_ must
be unifiable with a number, and the argument _L_ must be unifiable
with an atom representing the number.
*/
Yap_InitCPred("number_string", 2, p_number_string, 0);
Yap_InitCPred("number_codes", 2, p_number_codes, 0);
Yap_InitCPred("atom_number", 2, p_atom_number, 0);
/** @pred atom_number(? _Atom_,? _Number_)
The predicate holds when at least one of the arguments is ground
(otherwise, an error message will be displayed). If the argument
_Atom_ is an atom, _Number_ must be the number corresponding
to the characters in _Atom_, otherwise the characters in
_Atom_ must encode a number _Number_.
*/
Yap_InitCPred("string_number", 2, p_string_number, 0);
Yap_InitCPred("$atom_concat", 2, p_atom_concat2, 0);
Yap_InitCPred("$string_concat", 2, p_string_concat2, 0);
Yap_InitCPred("atomic_concat", 2, p_atomic_concat2, 0);
/** @pred atomic_concat(+ _As_,? _A_)
The predicate holds when the first argument is a list of atomic terms, and
the second unifies with the atom obtained by concatenating all the
atomic terms in the first list. The first argument thus may contain
atoms or numbers.
*/
Yap_InitCPred("atomic_concat", 3, p_atomic_concat3, 0);
Yap_InitCPred("atomics_to_string", 2, p_atomics_to_string2, 0);
Yap_InitCPred("atomics_to_string", 3, p_atomics_to_string3, 0);
@ -2117,3 +2243,7 @@ Yap_InitAtomPreds(void)
Yap_InitCPred("unhide", 1, p_unhide, SafePredFlag|SyncPredFlag);
Yap_InitCPred("$hidden", 1, p_hidden, SafePredFlag|SyncPredFlag);
}
/**
@}
*/

View File

@ -1104,6 +1104,14 @@ void Yap_InitAttVarPreds(void)
Yap_InitCPred("all_attvars", 1, p_all_attvars, 0);
CurrentModule = OldCurrentModule;
Yap_InitCPred("attvar", 1, p_is_attvar, SafePredFlag|TestPredFlag);
/** @pred attvar( _-Var_)
Succeed if _Var_ is an attributed variable.
*/
Yap_InitCPred("$att_bound", 1, p_attvar_bound, SafePredFlag|TestPredFlag);
}

55
C/bb.c
View File

@ -18,6 +18,26 @@
static char SccsId[] = "%W% %G%";
#endif
/** @defgroup BlackBoard The Blackboard
@ingroup YAPBuiltins
@{
YAP implements a blackboard in the style of the SICStus Prolog
blackboard. The blackboard uses the same underlying mechanism as the
internal data-base but has several important differences:
+ It is module aware, in contrast to the internal data-base.
+ Keys can only be atoms or integers, and not compound terms.
+ A single term can be stored per key.
+ An atomic update operation is provided; this is useful for
parallelism.
*/
#include "Yap.h"
#include "clause.h"
#ifndef NULL
@ -263,6 +283,14 @@ BBPut(Term t0, Term t2)
}
}
/** @pred bb_put(+ _Key_,? _Term_)
Store term table _Term_ in the blackboard under key _Key_. If a
previous term was stored under key _Key_ it is simply forgotten.
*/
static Int
p_bb_put( USES_REGS1 )
{
@ -294,6 +322,14 @@ BBGet(Term t, UInt arity USES_REGS)
}
}
/** @pred bb_get(+ _Key_,? _Term_)
Unify _Term_ with a term stored in the blackboard under key
_Key_, or fail silently if no such term exists.
*/
static Int
p_bb_get( USES_REGS1 )
{
@ -313,6 +349,14 @@ p_bb_get( USES_REGS1 )
return Yap_unify(ARG2,out);
}
/** @pred bb_delete(+ _Key_,? _Term_)
Delete any term stored in the blackboard under key _Key_ and unify
it with _Term_. Fail silently if no such term exists.
*/
static Int
p_bb_delete( USES_REGS1 )
{
@ -333,6 +377,14 @@ p_bb_delete( USES_REGS1 )
return Yap_unify(ARG2,out);
}
/** @pred bb_update( +_Key_, ?_Term_, ?_New_)
Atomically unify a term stored in the blackboard under key _Key_
with _Term_, and if the unification succeeds replace it by
_New_. Fail silently if no such term exists or if unification fails.
*/
static Int
p_bb_update( USES_REGS1 )
{
@ -378,3 +430,6 @@ Yap_InitBBPreds(void)
Yap_InitCPred("$resize_bb_int_keys", 1, p_resize_bb_int_keys, SafePredFlag|SyncPredFlag);
}
/**
@}
*/

View File

@ -564,6 +564,13 @@ Yap_InitBigNums(void)
Yap_InitCPred("$bignum", 1, p_is_bignum, SafePredFlag);
Yap_InitCPred("rational", 3, p_rational, 0);
Yap_InitCPred("rational", 1, p_is_rational, SafePredFlag);
/** @pred rational( _T_)
Checks whether `T` is a rational number.
*/
Yap_InitCPred("string", 1, p_is_string, SafePredFlag);
Yap_InitCPred("opaque", 1, p_is_opaque, SafePredFlag);
Yap_InitCPred("nb_set_bit", 2, p_nb_set_bit, SafePredFlag);

View File

@ -386,6 +386,7 @@
/**
@defgroup slotInterface Term Handles or Slots
@ingroup ChYInterface
@{
Term handles correspond to SWI-Prolog's term_t datatype: they are a safe representation
@ -458,6 +459,11 @@ X_API void YAP_SlotsToArgs(int HowMany, YAP_handle_t slot);
/// @}
/**
@addtogroup c-interface
@{
*/
static arity_t
current_arity(void)
{
@ -4185,3 +4191,6 @@ YAP_IntToAtom(Int i)
return SWI_Atoms[i];
}
/**
@}
*/

View File

@ -18,6 +18,40 @@
/** @defgroup Comparing_Terms Comparing Terms
@ingroup YAPBuiltins
@{
The following predicates are used to compare and order terms, using the
standard ordering:
+
variables come before numbers, numbers come before atoms which in turn
come before compound terms, i.e.: variables @< numbers @< atoms @<
compound terms.
+
Variables are roughly ordered by "age" (the "oldest" variable is put
first);
+
Floating point numbers are sorted in increasing order;
+
Rational numbers are sorted in increasing order;
+
Integers are sorted in increasing order;
+
Atoms are sorted in lexicographic order;
+
Compound terms are ordered first by arity of the main functor, then by
the name of the main functor, and finally by their arguments in
left-to-right order.
*/
#ifdef SCCS
static char SccsId[] = "%W% %G%";
#endif
@ -867,9 +901,92 @@ Yap_InitCmpPreds(void)
Yap_InitCmpPred(">=", 2, a_ge, SafePredFlag | BinaryPredFlag);
Yap_InitCPred("$a_compare", 3, p_acomp, TestPredFlag | SafePredFlag);
Yap_InitCmpPred("\\==", 2, a_noteq, BinaryPredFlag | SafePredFlag);
/** @pred _X_ \== _Y_ is iso
Terms _X_ and _Y_ are not strictly identical.
*/
Yap_InitCmpPred("@<", 2, a_gen_lt, BinaryPredFlag | SafePredFlag);
/** @pred _X_ @< _Y_ is iso
Term _X_ precedes term _Y_ in the standard order.
*/
Yap_InitCmpPred("@=<", 2, a_gen_le, BinaryPredFlag | SafePredFlag);
/** @pred _X_ @=< _Y_ is iso
Term _X_ does not follow term _Y_ in the standard order.
*/
Yap_InitCmpPred("@>", 2, a_gen_gt, BinaryPredFlag | SafePredFlag);
/** @pred _X_ @> _Y_ is iso
Term _X_ follows term _Y_ in the standard order.
*/
Yap_InitCmpPred("@>=", 2, a_gen_ge, BinaryPredFlag | SafePredFlag);
/** @pred _X_ @>= _Y_ is iso
Term _X_ does not precede term _Y_ in the standard order.
*/
Yap_InitCPred("compare", 3, p_compare, TestPredFlag | SafePredFlag);
/** @pred compare( _C_, _X_, _Y_) is iso
As a result of comparing _X_ and _Y_, _C_ may take one of
the following values:
+
`=` if _X_ and _Y_ are identical;
+
`<` if _X_ precedes _Y_ in the defined order;
+
`>` if _Y_ precedes _X_ in the defined order;
+ _X_ == _Y_ is iso
Succeeds if terms _X_ and _Y_ are strictly identical. The
difference between this predicate and =/2 is that, if one of the
arguments is a free variable, it only succeeds when they have already
been unified.
~~~~~{.prolog}
?- X == Y.
~~~~~
fails, but,
~~~~~{.prolog}
?- X = Y, X == Y.
~~~~~
succeeds.
~~~~~{.prolog}
?- X == 2.
~~~~~
fails, but,
~~~~~{.prolog}
?- X = 2, X == 2.
~~~~~
succeeds.
*/
}
/**
@}
*/

175
C/dbase.c Executable file → Normal file
View File

@ -18,6 +18,85 @@
static char SccsId[] = "%W% %G%";
#endif
/** @defgroup Internal_Database Internal Data Base
@ingroup YAPBuiltins
@{
Some programs need global information for, e.g. counting or collecting
data obtained by backtracking. As a rule, to keep this information, the
internal data base should be used instead of asserting and retracting
clauses (as most novice programmers do), .
In YAP (as in some other Prolog systems) the internal data base (i.d.b.
for short) is faster, needs less space and provides a better insulation of
program and data than using asserted/retracted clauses.
The i.d.b. is implemented as a set of terms, accessed by keys that
unlikely what happens in (non-Prolog) data bases are not part of the
term. Under each key a list of terms is kept. References are provided so that
terms can be identified: each term in the i.d.b. has a unique reference
(references are also available for clauses of dynamic predicates).
There is a strong analogy between the i.d.b. and the way dynamic
predicates are stored. In fact, the main i.d.b. predicates might be
implemented using dynamic predicates:
~~~~~
recorda(X,T,R) :- asserta(idb(X,T),R).
recordz(X,T,R) :- assertz(idb(X,T),R).
recorded(X,T,R) :- clause(idb(X,T),R).
~~~~~
We can take advantage of this, the other way around, as it is quite
easy to write a simple Prolog interpreter, using the i.d.b.:
~~~~~
asserta(G) :- recorda(interpreter,G,_).
assertz(G) :- recordz(interpreter,G,_).
retract(G) :- recorded(interpreter,G,R), !, erase(R).
call(V) :- var(V), !, fail.
call((H :- B)) :- !, recorded(interpreter,(H :- B),_), call(B).
call(G) :- recorded(interpreter,G,_).
~~~~~
In YAP, much attention has been given to the implementation of the
i.d.b., especially to the problem of accelerating the access to terms kept in
a large list under the same key. Besides using the key, YAP uses an internal
lookup function, transparent to the user, to find only the terms that might
unify. For instance, in a data base containing the terms
~~~~~
b
b(a)
c(d)
e(g)
b(X)
e(h)
~~~~~
stored under the key k/1, when executing the query
~~~~~
:- recorded(k(_),c(_),R).
~~~~~
`recorded` would proceed directly to the third term, spending almost the
time as if `a(X)` or `b(X)` was being searched.
The lookup function uses the functor of the term, and its first three
arguments (when they exist). So, `recorded(k(_),e(h),_)` would go
directly to the last term, while `recorded(k(_),e(_),_)` would find
first the fourth term, and then, after backtracking, the last one.
This mechanism may be useful to implement a sort of hierarchy, where
the functors of the terms (and eventually the first arguments) work as
secondary keys.
In the YAP's i.d.b. an optimized representation is used for
terms without free variables. This results in a faster retrieval of terms
and better space usage. Whenever possible, avoid variables in terms in terms stored in the i.d.b.
*/
#include "Yap.h"
#include "clause.h"
#include "yapio.h"
@ -5477,24 +5556,106 @@ void
Yap_InitDBPreds(void)
{
Yap_InitCPred("recorded", 3, p_recorded, SyncPredFlag);
/** @pred recorded(+ _K_, _T_, _R_)
Searches in the internal database under the key _K_, a term that
unifies with _T_ and whose reference matches _R_. This
built-in may be used in one of two ways:
+ _K_ may be given, in this case the built-in will return all
elements of the internal data-base that match the key.
+ _R_ may be given, if so returning the key and element that
match the reference.
*/
Yap_InitCPred("recorda", 3, p_rcda, SyncPredFlag);
/** @pred recorda(+ _K_, _T_,- _R_)
Makes term _T_ the first record under key _K_ and unifies _R_
with its reference.
*/
Yap_InitCPred("recordz", 3, p_rcdz, SyncPredFlag);
/** @pred recordz(+ _K_, _T_,- _R_)
Makes term _T_ the last record under key _K_ and unifies _R_
with its reference.
*/
Yap_InitCPred("$still_variant", 2, p_still_variant, SyncPredFlag);
Yap_InitCPred("recorda_at", 3, p_rcda_at, SyncPredFlag);
/** @pred recorda_at(+ _R0_, _T_,- _R_)
Makes term _T_ the record preceding record with reference
_R0_, and unifies _R_ with its reference.
*/
Yap_InitCPred("recordz_at", 3, p_rcdz_at, SyncPredFlag);
/** @pred recordz_at(+ _R0_, _T_,- _R_)
Makes term _T_ the record following record with reference
_R0_, and unifies _R_ with its reference.
*/
Yap_InitCPred("$recordap", 3, p_rcdap, SyncPredFlag);
Yap_InitCPred("$recordzp", 3, p_rcdzp, SyncPredFlag);
Yap_InitCPred("$recordap", 4, p_drcdap, SyncPredFlag);
Yap_InitCPred("$recordzp", 4, p_drcdzp, SyncPredFlag);
Yap_InitCPred("erase", 1, p_erase, SafePredFlag|SyncPredFlag);
/** @pred erase(+ _R_)
The term referred to by _R_ is erased from the internal database. If
reference _R_ does not exist in the database, `erase` just fails.
*/
Yap_InitCPred("$erase_clause", 2, p_erase_clause, SafePredFlag|SyncPredFlag);
Yap_InitCPred("increase_reference_count", 1, p_increase_reference_counter, SafePredFlag|SyncPredFlag);
Yap_InitCPred("decrease_reference_count", 1, p_decrease_reference_counter, SafePredFlag|SyncPredFlag);
Yap_InitCPred("current_reference_count", 2, p_current_reference_counter, SafePredFlag|SyncPredFlag);
Yap_InitCPred("erased", 1, p_erased, TestPredFlag | SafePredFlag|SyncPredFlag);
/** @pred erased(+ _R_)
Succeeds if the object whose database reference is _R_ has been
erased.
*/
Yap_InitCPred("instance", 2, p_instance, SyncPredFlag);
/** @pred instance(+ _R_,- _T_)
If _R_ refers to a clause or a recorded term, _T_ is unified
with its most general instance. If _R_ refers to an unit clause
_C_, then _T_ is unified with ` _C_ :- true`. When
_R_ is not a reference to an existing clause or to a recorded term,
this goal fails.
*/
Yap_InitCPred("$instance_module", 2, p_instance_module, SyncPredFlag);
Yap_InitCPred("eraseall", 1, p_eraseall, SafePredFlag|SyncPredFlag);
/** @pred eraseall(+ _K_)
All terms belonging to the key `K` are erased from the internal
database. The predicate always succeeds.
*/
Yap_InitCPred("$record_stat_source", 4, p_rcdstatp, SafePredFlag|SyncPredFlag);
Yap_InitCPred("$some_recordedp", 1, p_somercdedp, SafePredFlag|SyncPredFlag);
Yap_InitCPred("$first_instance", 3, p_first_instance, SafePredFlag|SyncPredFlag);
@ -5512,6 +5673,16 @@ Yap_InitDBPreds(void)
Yap_InitCPred("$fetch_reference_from_index", 3, p_fetch_reference_from_index, SafePredFlag|SyncPredFlag);
Yap_InitCPred("$resize_int_keys", 1, p_resize_int_keys, SafePredFlag|SyncPredFlag);
Yap_InitCPred("key_statistics", 4, p_key_statistics, SyncPredFlag);
/** @pred key_statistics(+ _K_,- _Entries_,- _Size_,- _IndexSize_)
Returns several statistics for a key _K_. Currently, it says how
many entries we have for that key, _Entries_, what is the
total size spent on entries, _Size_, and what is the amount of
space spent in indices.
*/
Yap_InitCPred("$lu_statistics", 5, p_lu_statistics, SyncPredFlag);
Yap_InitCPred("total_erased", 4, p_total_erased, SyncPredFlag);
Yap_InitCPred("key_erased_statistics", 5, p_key_erased_statistics, SyncPredFlag);
@ -5530,3 +5701,7 @@ Yap_InitBackDB(void)
Yap_InitCPredBack("$current_immediate_key", 2, 4, init_current_key, cont_current_key,
SyncPredFlag);
}
/**
@}
*/

View File

@ -554,6 +554,20 @@ Yap_InitEval(void)
Yap_InitCPred("isinf", 1, p_isinf, TestPredFlag);
Yap_InitCPred("logsum", 3, p_logsum, TestPredFlag);
Yap_InitCPredBack("between", 3, 2, init_between, cont_between, 0);
/** @pred between(+ _Low_,+ _High_,? _Value_)
_Low_ and _High_ are integers, _High_ less or equal than
_Low_. If _Value_ is an integer, _Low_ less or equal than
_Value_ less or equal than _High_. When _Value_ is a
variable it is successively bound to all integers between _Low_ and
_High_. If _High_ is `inf`, between/3 is true iff
_Value_ less or equal than _Low_, a feature that is particularly
interesting for generating integers from a certain value.
*/
}
/**

View File

@ -18,6 +18,91 @@
static char SccsId[] = "%W% %G%";
#endif
/**
@file globals.c
@defgroup Global_Variables Global Variables
@ingroup YAPBuiltins
@{
Global variables are associations between names (atoms) and
terms. They differ in various ways from storing information using
assert/1 or recorda/3.
+ The value lives on the Prolog (global) stack. This implies that
lookup time is independent from the size of the term. This is
particularly interesting for large data structures such as parsed XML
documents or the CHR global constraint store.
+ They support both global assignment using nb_setval/2 and
backtrackable assignment using b_setval/2.
+ Only one value (which can be an arbitrary complex Prolog term)
can be associated to a variable at a time.
+ Their value cannot be shared among threads. Each thread has its own
namespace and values for global variables.
Currently global variables are scoped globally. We may consider module
scoping in future versions. Both b_setval/2 and
nb_setval/2 implicitly create a variable if the referenced name
does not already refer to a variable.
Global variables may be initialised from directives to make them
available during the program lifetime, but some considerations are
necessary for saved-states and threads. Saved-states to not store
global variables, which implies they have to be declared with
initialization/1 to recreate them after loading the saved
state. Each thread has its own set of global variables, starting with
an empty set. Using `thread_initialization/1` to define a global
variable it will be defined, restored after reloading a saved state
and created in all threads that are created after the
registration. Finally, global variables can be initialised using the
exception hook called exception/3. The latter technique is used
by CHR.
SWI-Prolog global variables are associations between names (atoms) and
terms. They differ in various ways from storing information using
assert/1 or recorda/3.
+ The value lives on the Prolog (global) stack. This implies
that lookup time is independent from the size of the term.
This is particulary interesting for large data structures
such as parsed XML documents or the CHR global constraint
store.
They support both global assignment using nb_setval/2 and
backtrackable assignment using b_setval/2.
+ Only one value (which can be an arbitrary complex Prolog
term) can be associated to a variable at a time.
+ Their value cannot be shared among threads. Each thread
has its own namespace and values for global variables.
+ Currently global variables are scoped globally. We may
consider module scoping in future versions.
Both b_setval/2 and nb_setval/2 implicitly create a variable if the
referenced name does not already refer to a variable.
Global variables may be initialised from directives to make them
available during the program lifetime, but some considerations are
necessary for saved-states and threads. Saved-states to not store global
variables, which implies they have to be declared with initialization/1
to recreate them after loading the saved state. Each thread has
its own set of global variables, starting with an empty set. Using
`thread_inititialization/1` to define a global variable it will be
defined, restored after reloading a saved state and created in all
threads that are created <em>after</em> the registration.
*/
#include "Yap.h"
#include "Yatom.h"
#include "YapHeap.h"
@ -2602,14 +2687,173 @@ void Yap_InitGlobals(void)
Yap_InitCPred("$allocate_arena", 2, p_allocate_arena, 0);
Yap_InitCPred("arena_size", 1, p_default_arena_size, 0);
Yap_InitCPred("b_setval", 2, p_b_setval, SafePredFlag);
/** @pred b_setval(+ _Name_, + _Value_)
Associate the term _Value_ with the atom _Name_ or replaces
the currently associated value with _Value_. If _Name_ does
not refer to an existing global variable a variable with initial value
[] is created (the empty list). On backtracking the assignment is
reversed.
*/
/** @pred b_setval(+ _Name_,+ _Value_)
Associate the term _Value_ with the atom _Name_ or replaces
the currently associated value with _Value_. If _Name_ does
not refer to an existing global variable a variable with initial value
`[]` is created (the empty list). On backtracking the
assignment is reversed.
*/
Yap_InitCPred("nb_setval", 2, p_nb_setval, 0L);
/** @pred nb_setval(+ _Name_, + _Value_)
Associates a copy of _Value_ created with duplicate_term/2 with
the atom _Name_. Note that this can be used to set an initial
value other than `[]` prior to backtrackable assignment.
*/
/** @pred nb_setval(+ _Name_,+ _Value_)
Associates a copy of _Value_ created with duplicate_term/2
with the atom _Name_. Note that this can be used to set an
initial value other than `[]` prior to backtrackable assignment.
*/
Yap_InitCPred("nb_set_shared_val", 2, p_nb_set_shared_val, 0L);
/** @pred nb_set_shared_val(+ _Name_, + _Value_)
Associates the term _Value_ with the atom _Name_, but sharing
non-backtrackable terms. This may be useful if you want to rewrite a
global variable so that the new copy will survive backtracking, but
you want to share structure with the previous term.
The next example shows the differences between the three built-ins:
~~~~~
?- nb_setval(a,a(_)),nb_getval(a,A),nb_setval(b,t(C,A)),nb_getval(b,B).
A = a(_A),
B = t(_B,a(_C)) ?
?- nb_setval(a,a(_)),nb_getval(a,A),nb_set_shared_val(b,t(C,A)),nb_getval(b,B).
?- nb_setval(a,a(_)),nb_getval(a,A),nb_linkval(b,t(C,A)),nb_getval(b,B).
A = a(_A),
B = t(C,a(_A)) ?
~~~~~
*/
Yap_InitCPred("nb_linkval", 2, p_nb_linkval, 0L);
/** @pred nb_linkval(+ _Name_, + _Value_)
Associates the term _Value_ with the atom _Name_ without
copying it. This is a fast special-purpose variation of nb_setval/2
intended for expert users only because the semantics on backtracking
to a point before creating the link are poorly defined for compound
terms. The principal term is always left untouched, but backtracking
behaviour on arguments is undone if the original assignment was
trailed and left alone otherwise, which implies that the history that
created the term affects the behaviour on backtracking. Please
consider the following example:
~~~~~
demo_nb_linkval :-
T = nice(N),
( N = world,
nb_linkval(myvar, T),
fail
; nb_getval(myvar, V),
writeln(V)
).
~~~~~
*/
Yap_InitCPred("$nb_getval", 3, p_nb_getval, SafePredFlag);
Yap_InitCPred("nb_setarg", 3, p_nb_setarg, 0L);
/** @pred nb_setarg(+{Arg], + _Term_, + _Value_)
Assigns the _Arg_-th argument of the compound term _Term_ with
the given _Value_ as setarg/3, but on backtracking the assignment
is not reversed. If _Term_ is not atomic, it is duplicated using
duplicate_term/2. This predicate uses the same technique as
nb_setval/2. We therefore refer to the description of
nb_setval/2 for details on non-backtrackable assignment of
terms. This predicate is compatible to GNU-Prolog
`setarg(A,T,V,false)`, removing the type-restriction on
_Value_. See also nb_linkarg/3. Below is an example for
counting the number of solutions of a goal. Note that this
implementation is thread-safe, reentrant and capable of handling
exceptions. Realising these features with a traditional implementation
based on assert/retract or flag/3 is much more complicated.
~~~~~
succeeds_n_times(Goal, Times) :-
Counter = counter(0),
( Goal,
arg(1, Counter, N0),
N is N0 + 1,
nb_setarg(1, Counter, N),
fail
; arg(1, Counter, Times)
).
~~~~~
*/
Yap_InitCPred("nb_set_shared_arg", 3, p_nb_set_shared_arg, 0L);
/** @pred nb_set_shared_arg(+ _Arg_, + _Term_, + _Value_)
As nb_setarg/3, but like nb_linkval/2 it does not
duplicate the global sub-terms in _Value_. Use with extreme care
and consult the documentation of nb_linkval/2 before use.
*/
Yap_InitCPred("nb_linkarg", 3, p_nb_linkarg, 0L);
/** @pred nb_linkarg(+ _Arg_, + _Term_, + _Value_)
As nb_setarg/3, but like nb_linkval/2 it does not
duplicate _Value_. Use with extreme care and consult the
documentation of nb_linkval/2 before use.
*/
Yap_InitCPred("nb_delete", 1, p_nb_delete, 0L);
/** @pred nb_delete(+ _Name_)
Delete the named global variable.
Global variables have been introduced by various Prolog
implementations recently. We follow the implementation of them in
SWI-Prolog, itself based on hProlog by Bart Demoen.
GNU-Prolog provides a rich set of global variables, including
arrays. Arrays can be implemented easily in YAP and SWI-Prolog using
functor/3 and `setarg/3` due to the unrestricted arity of
compound terms.
@} */
Yap_InitCPred("nb_create", 3, p_nb_create, 0L);
Yap_InitCPred("nb_create", 4, p_nb_create2, 0L);
Yap_InitCPredBack("$nb_current", 1, 1, init_current_nb, cont_current_nb, SafePredFlag);
@ -2647,3 +2891,7 @@ void Yap_InitGlobals(void)
Yap_InitCPred("nb_beam_size", 2, p_nb_beam_size, SafePredFlag);
CurrentModule = cm;
}
/**
@}
*/

View File

@ -47,6 +47,41 @@
* *
*************************************************************************/
/** @defgroup Tick_Profiler Tick Profiler
@ingroup Profiling
@{
The tick profiler works by interrupting the Prolog code every so often
and checking at each point the code was. The profiler must be able to
retrace the state of the abstract machine at every moment. The major
advantage of this approach is that it gives the actual amount of time
being spent per procedure, or whether garbage collection dominates
execution time. The major drawback is that tracking down the state of
the abstract machine may take significant time, and in the worst case
may slow down the whole execution.
The following procedures are available:
+ profinit
Initialise the data-structures for the profiler. Unnecessary for
dynamic profiler.
+ profon
Start profiling.
+ profoff
Stop profiling.
*/
#ifdef SCCS
static char SccsId[] = "%W% %G%";
#endif
@ -63,6 +98,7 @@ typedef greg_t context_reg;
#elif defined(__i386__) && defined (__linux__)
#include <ucontext.h>
typedef greg_t context_reg;
@ -1185,3 +1221,8 @@ Yap_InitLowProf(void)
Yap_InitCPred("showprofres", 4, getpredinfo, SafePredFlag);
#endif
}
/**
@}
*/

143
C/index.c
View File

@ -455,6 +455,149 @@
static char SccsId[] = "%W% %G%";
#endif
/**
@file index.c
@defgroup Indexing Indexing
@ingroup YAPProgramming
The
indexation mechanism restricts the set of clauses to be tried in a
procedure by using information about the status of the instantiated
arguments of the goal. These arguments are then used as a key,
selecting a restricted set of a clauses from all the clauses forming the
procedure.
As an example, the two clauses for concatenate:
~~~~~
concatenate([],L,L).
concatenate([H|T],A,[H|NT]) :- concatenate(T,A,NT).
~~~~~
If the first argument for the goal is a list, then only the second clause
is of interest. If the first argument is the nil atom, the system needs to
look only for the first clause. The indexation generates instructions that
test the value of the first argument, and then proceed to a selected clause,
or group of clauses.
Note that if the first argument was a free variable, then both clauses
should be tried. In general, indexation will not be useful if the first
argument is a free variable.
When activating a predicate, a Prolog system needs to store state
information. This information, stored in a structure known as choice point
or fail point, is necessary when backtracking to other clauses for the
predicate. The operations of creating and using a choice point are very
expensive, both in the terms of space used and time spent.
Creating a choice point is not necessary if there is only a clause for
the predicate as there are no clauses to backtrack to. With indexation, this
situation is extended: in the example, if the first argument was the atom
nil, then only one clause would really be of interest, and it is pointless to
create a choice point. This feature is even more useful if the first argument
is a list: without indexation, execution would try the first clause, creating
a choice point. The clause would fail, the choice point would then be used to
restore the previous state of the computation and the second clause would
be tried. The code generated by the indexation mechanism would behave
much more efficiently: it would test the first argument and see whether it
is a list, and then proceed directly to the second clause.
An important side effect concerns the use of "cut". In the above
example, some programmers would use a "cut" in the first clause just to
inform the system that the predicate is not backtrackable and force the
removal the choice point just created. As a result, less space is needed but
with a great loss in expressive power: the "cut" would prevent some uses of
the procedure, like generating lists through backtracking. Of course, with
indexation the "cut" becomes useless: the choice point is not even created.
Indexation is also very important for predicates with a large number
of clauses that are used like tables:
~~~~~
logician(aristoteles,greek).
logician(frege,german).
logician(russel,english).
logician(godel,german).
logician(whitehead,english).
~~~~~
An interpreter like C-Prolog, trying to answer the query:
~~~~~
?- logician(godel,X).
~~~~~
would blindly follow the standard Prolog strategy, trying first the
first clause, then the second, the third and finally finding the
relevant clause. Also, as there are some more clauses after the
important one, a choice point has to be created, even if we know the
next clauses will certainly fail. A "cut" would be needed to prevent
some possible uses for the procedure, like generating all logicians. In
this situation, the indexing mechanism generates instructions that
implement a search table. In this table, the value of the first argument
would be used as a key for fast search of possibly matching clauses. For
the query of the last example, the result of the search would be just
the fourth clause, and again there would be no need for a choice point.
If the first argument is a complex term, indexation will select clauses
just by testing its main functor. However, there is an important
exception: if the first argument of a clause is a list, the algorithm
also uses the list's head if not a variable. For instance, with the
following clauses,
~~~~~
rules([],B,B).
rules([n(N)|T],I,O) :- rules_for_noun(N,I,N), rules(T,N,O).
rules([v(V)|T],I,O) :- rules_for_verb(V,I,N), rules(T,N,O).
rules([q(Q)|T],I,O) :- rules_for_qualifier(Q,I,N), rules(T,N,O).
~~~~~
if the first argument of the goal is a list, its head will be tested, and only
the clauses matching it will be tried during execution.
Some advice on how to take a good advantage of this mechanism:
+
Try to make the first argument an input argument.
+
Try to keep together all clauses whose first argument is not a
variable, that will decrease the number of tests since the other clauses are
always tried.
+
Try to avoid predicates having a lot of clauses with the same key.
For instance, the procedure:
~~~~~
type(n(mary),person).
type(n(john), person).
type(n(chair),object).
type(v(eat),active).
type(v(rest),passive).
~~~~~
becomes more efficient with:
~~~~~
type(n(N),T) :- type_of_noun(N,T).
type(v(V),T) :- type_of_verb(V,T).
type_of_noun(mary,person).
type_of_noun(john,person).
type_of_noun(chair,object).
type_of_verb(eat,active).
type_of_verb(rest,passive).
~~~~~
*/
/*
* This file compiles and removes the indexation code for the prolog compiler
*

View File

@ -14,7 +14,16 @@
* comments: C-version for inline code used in meta-calls *
* *
*************************************************************************/
/** @defgroup YAP_Terms Predicates on terms
@ingroup YAPBuiltins
@{
*/
#define IN_INLINES_C 1
#include "absmi.h"
@ -38,6 +47,13 @@ static Int p_arg( USES_REGS1 );
static Int p_functor( USES_REGS1 );
/** @pred atom( _T_) is iso
Succeeds if and only if _T_ is currently instantiated to an atom.
*/
static Int
p_atom( USES_REGS1 )
{ /* atom(?) */
@ -59,6 +75,13 @@ p_atom( USES_REGS1 )
ENDD(d0);
}
/** @pred atomic(T) is iso
Checks whether _T_ is an atomic symbol (atom or number).
*/
static Int
p_atomic( USES_REGS1 )
{ /* atomic(?) */
@ -80,6 +103,13 @@ p_atomic( USES_REGS1 )
ENDD(d0);
}
/** @pred integer( _T_) is iso
Succeeds if and only if _T_ is currently instantiated to an integer.
*/
static Int
p_integer( USES_REGS1 )
{ /* integer(?,?) */
@ -118,6 +148,13 @@ p_integer( USES_REGS1 )
ENDD(d0);
}
/** @pred number( _T_) is iso
Checks whether `T` is an integer, rational or a float.
*/
static Int
p_number( USES_REGS1 )
{ /* number(?) */
@ -157,6 +194,13 @@ p_number( USES_REGS1 )
ENDD(d0);
}
/** @pred db_reference( _T_)
Checks whether _T_ is a database reference.
*/
static Int
p_db_ref( USES_REGS1 )
{ /* db_reference(?,?) */
@ -178,6 +222,13 @@ p_db_ref( USES_REGS1 )
ENDD(d0);
}
/** @pred primitive( ?_T_)
Checks whether _T_ is an atomic term or a database reference.
*/
static Int
p_primitive( USES_REGS1 )
{ /* primitive(?) */
@ -199,6 +250,13 @@ p_primitive( USES_REGS1 )
ENDD(d0);
}
/** @pred float( _T_) is iso
Checks whether _T_ is a floating point number.
*/
static Int
p_float( USES_REGS1 )
{ /* float(?) */
@ -220,6 +278,13 @@ p_float( USES_REGS1 )
ENDD(d0);
}
/** @pred compound( _T_) is iso
Checks whether _T_ is a compound term.
*/
static Int
p_compound( USES_REGS1 )
{ /* compound(?) */
@ -247,6 +312,13 @@ p_compound( USES_REGS1 )
ENDD(d0);
}
/** @pred nonvar( _T_) is iso
The opposite of `var( _T_)`.
*/
static Int
p_nonvar( USES_REGS1 )
{ /* nonvar(?) */
@ -263,6 +335,13 @@ p_nonvar( USES_REGS1 )
ENDD(d0);
}
/** @pred var( _T_) is iso
Succeeds if _T_ is currently a free variable, otherwise fails.
*/
static Int
p_var( USES_REGS1 )
{ /* var(?) */
@ -279,6 +358,13 @@ p_var( USES_REGS1 )
ENDD(d0);
}
/** @pred _X_ = _Y_ is iso
Tries to unify terms _X_ and _Y_.
*/
static Int
p_equal( USES_REGS1 )
{ /* ?=? */
@ -371,6 +457,37 @@ eq(Term t1, Term t2 USES_REGS)
ENDD(d0);
}
/** @pred ?_X_ == ?_Y_ is iso
Succeeds if terms _X_ and _Y_ are strictly identical. The
difference between this predicate and =/2 is that, if one of the
arguments is a free variable, it only succeeds when they have already
been unified.
~~~~~{.prolog}
?- X == Y.
~~~~~
fails, but,
~~~~~{.prolog}
?- X = Y, X == Y.
~~~~~
succeeds.
~~~~~{.prolog}
?- X == 2.
~~~~~
fails, but,
~~~~~{.prolog}
?- X = 2, X == 2.
~~~~~
succeeds.
*/
static Int
p_eq( USES_REGS1 )
{ /* ? == ? */
@ -384,6 +501,13 @@ Yap_eq(Term t1, Term t2)
return eq(t1,t2 PASS_REGS);
}
/** @pred _X_ \= _Y_ is iso
Succeeds if terms _X_ and _Y_ are not unifiable.
*/
static Int
p_dif( USES_REGS1 )
{ /* ? \= ? */
@ -492,6 +616,20 @@ p_dif( USES_REGS1 )
ENDD(d0);
}
/** @pred arg(+ _N_,+ _T_, _A_) is iso
Succeeds if the argument _N_ of the term _T_ unifies with
_A_. The arguments are numbered from 1 to the arity of the term.
The current version will generate an error if _T_ or _N_ are
unbound, if _T_ is not a compound term, of if _N_ is not a positive
integer. Note that previous versions of YAP would fail silently
under these errors.
*/
static Int
p_arg( USES_REGS1 )
{ /* arg(?,?,?) */
@ -588,6 +726,26 @@ p_arg( USES_REGS1 )
}
/** @pred functor( _T_, _F_, _N_) is iso
The top functor of term _T_ is named _F_ and has arity _N_.
When _T_ is not instantiated, _F_ and _N_ must be. If
_N_ is 0, _F_ must be an atomic symbol, which will be unified
with _T_. If _N_ is not 0, then _F_ must be an atom and
_T_ becomes instantiated to the most general term having functor
_F_ and arity _N_. If _T_ is instantiated to a term then
_F_ and _N_ are respectively unified with its top functor name
and arity.
In the current version of YAP the arity _N_ must be an
integer. Previous versions allowed evaluable expressions, as long as the
expression would evaluate to an integer. This feature is not available
in the ISO Prolog standard.
*/
static Int
p_functor( USES_REGS1 ) /* functor(?,?,?) */
{
@ -954,3 +1112,7 @@ Yap_InitInlines(void)
CurrentModule = cm;
}
/**
@}
*/

34
C/iopreds.c Executable file → Normal file
View File

@ -984,12 +984,46 @@ Yap_InitIOPreds(void)
Yap_InitCPred ("$change_type_of_char", 2, p_change_type_of_char, SafePredFlag|SyncPredFlag);
Yap_InitCPred ("$type_of_char", 2, p_type_of_char, SafePredFlag|SyncPredFlag);
Yap_InitCPred ("char_conversion", 2, p_char_conversion, SyncPredFlag);
/** @pred char_conversion(+ _IN_,+ _OUT_) is iso
While reading terms convert unquoted occurrences of the character
_IN_ to the character _OUT_. Both _IN_ and _OUT_ must be
bound to single characters atoms.
Character conversion only works if the flag `char_conversion` is
on. This is default in the `iso` and `sicstus` language
modes. As an example, character conversion can be used for instance to
convert characters from the ISO-LATIN-1 character set to ASCII.
If _IN_ is the same character as _OUT_, char_conversion/2
will remove this conversion from the table.
*/
Yap_InitCPred ("$current_char_conversion", 2, p_current_char_conversion, SyncPredFlag);
Yap_InitCPred ("$all_char_conversions", 1, p_all_char_conversions, SyncPredFlag);
Yap_InitCPred ("$force_char_conversion", 0, p_force_char_conversion, SyncPredFlag);
Yap_InitCPred ("$disable_char_conversion", 0, p_disable_char_conversion, SyncPredFlag);
#if HAVE_SELECT
// Yap_InitCPred ("stream_select", 3, p_stream_select, SafePredFlag|SyncPredFlag);
/** @pred stream_select(+ _STREAMS_,+ _TIMEOUT_,- _READSTREAMS_)
Given a list of open _STREAMS_ opened in read mode and a _TIMEOUT_
return a list of streams who are now available for reading.
If the _TIMEOUT_ is instantiated to `off`,
stream_select/3 will wait indefinitely for a stream to become
open. Otherwise the timeout must be of the form `SECS:USECS` where
`SECS` is an integer gives the number of seconds to wait for a timeout
and `USECS` adds the number of micro-seconds.
This built-in is only defined if the system call `select` is
available in the system.
*/
#endif
Yap_InitCPred ("$float_format", 1, p_float_format, SafePredFlag|SyncPredFlag);
Yap_InitCPred ("$style_checker", 1, p_style_checker, SyncPredFlag);

6
C/load_foreign.c Executable file → Normal file
View File

@ -234,6 +234,12 @@ Yap_InitLoadForeign( void )
Yap_InitCPred("$open_shared_objects", 0, p_open_shared_objects, SafePredFlag);
Yap_InitCPred("$open_shared_object", 3, p_open_shared_object, SyncPredFlag);
Yap_InitCPred("close_shared_object", 1, p_close_shared_object, SyncPredFlag|SafePredFlag);
/** @pred close_shared_object(+ _Handle_)
Detach the shared object identified by _Handle_.
*/
Yap_InitCPred("call_shared_object_function", 2, p_call_shared_object_function, SyncPredFlag);
Yap_InitCPred("$obj_suffix", 1, p_obj_suffix, SafePredFlag);
}

View File

@ -15,6 +15,29 @@
* *
*************************************************************************/
/** @defgroup Term_Modification Term Modification
@ingroup YAPBuiltins
@{
It is sometimes useful to change the value of instantiated
variables. Although, this is against the spirit of logic programming, it
is sometimes useful. As in other Prolog systems, YAP has
several primitives that allow updating Prolog terms. Note that these
primitives are also backtrackable.
The `setarg/3` primitive allows updating any argument of a Prolog
compound terms. The `mutable` family of predicates provides
<em>mutable variables</em>. They should be used instead of `setarg/3`,
as they allow the encapsulation of accesses to updatable
variables. Their implementation can also be more efficient for long
deterministic computations.
*/
#include "Yap.h"
#ifdef MULTI_ASSIGNMENT_VARIABLES
@ -287,9 +310,49 @@ Yap_InitMaVarCPreds(void)
#ifdef MULTI_ASSIGNMENT_VARIABLES
/* The most famous contributions of SICStus to the Prolog language */
Yap_InitCPred("setarg", 3, p_setarg, SafePredFlag);
/** @pred setarg(+ _I_,+ _S_,? _T_)
Set the value of the _I_th argument of term _S_ to term _T_.
*/
Yap_InitCPred("create_mutable", 2, p_create_mutable, SafePredFlag);
/** @pred create_mutable(+ _D_,- _M_)
Create new mutable variable _M_ with initial value _D_.
*/
Yap_InitCPred("get_mutable", 2, p_get_mutable, SafePredFlag);
/** @pred get_mutable(? _D_,+ _M_)
Unify the current value of mutable term _M_ with term _D_.
*/
Yap_InitCPred("update_mutable", 2, p_update_mutable, SafePredFlag);
/** @pred update_mutable(+ _D_,+ _M_)
Set the current value of mutable term _M_ to term _D_.
*/
Yap_InitCPred("is_mutable", 1, p_is_mutable, SafePredFlag);
/** @pred is_mutable(? _D_)
Holds if _D_ is a mutable term.
*/
#endif
}
/**
@}
*/

53
C/stdpreds.c Executable file → Normal file
View File

@ -1877,11 +1877,54 @@ Yap_InitCPreds(void)
{
/* numerical comparison */
Yap_InitCPred("set_value", 2, p_setval, SafePredFlag|SyncPredFlag);
/** @pred set_value(+ _A_,+ _C_)
Associate atom _A_ with constant _C_.
The `set_value` and `get_value` built-ins give a fast alternative to
the internal data-base. This is a simple form of implementing a global
counter.
~~~~~
read_and_increment_counter(Value) :-
get_value(counter, Value),
Value1 is Value+1,
set_value(counter, Value1).
~~~~~
This predicate is YAP specific.
*/
Yap_InitCPred("get_value", 2, p_value, TestPredFlag|SafePredFlag|SyncPredFlag);
/** @pred get_value(+ _A_,- _V_)
In YAP, atoms can be associated with constants. If one such
association exists for atom _A_, unify the second argument with the
constant. Otherwise, unify _V_ with `[]`.
This predicate is YAP specific.
*/
Yap_InitCPred("$values", 3, p_values, SafePredFlag|SyncPredFlag);
/* general purpose */
Yap_InitCPred("$opdec", 4, p_opdec, SafePredFlag|SyncPredFlag);
Yap_InitCPred("=..", 2, p_univ, 0);
/** @pred _T_ =.. _L_ is iso
The list _L_ is built with the functor and arguments of the term
_T_. If _T_ is instantiated to a variable, then _L_ must be
instantiated either to a list whose head is an atom, or to a list
consisting of just a number.
*/
Yap_InitCPred("$statistics_trail_max", 1, p_statistics_trail_max, SafePredFlag|SyncPredFlag);
Yap_InitCPred("$statistics_heap_max", 1, p_statistics_heap_max, SafePredFlag|SyncPredFlag);
Yap_InitCPred("$statistics_global_max", 1, p_statistics_global_max, SafePredFlag|SyncPredFlag);
@ -1902,6 +1945,16 @@ Yap_InitCPreds(void)
Yap_InitCPred("$set_yap_flags", 2, p_set_yap_flags, SafePredFlag|SyncPredFlag);
Yap_InitCPred("$system_mode", 1, p_system_mode, SafePredFlag|SyncPredFlag);
Yap_InitCPred("abort", 0, p_abort, SyncPredFlag);
/** @pred abort
Abandons the execution of the current goal and returns to top level. All
break levels (see break/0 below) are terminated. It is mainly
used during debugging or after a serious execution error, to return to
the top-level.
*/
Yap_InitCPred("$break", 1, p_break, SafePredFlag);
#ifdef BEAM
Yap_InitCPred("@", 0, eager_split, SafePredFlag);

18
C/sysbits.c Executable file → Normal file
View File

@ -18,6 +18,10 @@
static char SccsId[] = "%W% %G%";
#endif
/**
@addtogroup YAPOS
*/
/*
* In this routine we shall try to include the inevitably machine dependant
* routines. These include, for the moment : Time, A rudimentary form of
@ -2962,9 +2966,23 @@ Yap_InitSysPreds(void)
#endif
Yap_InitCPred ("log_event", 1, p_log_event, SafePredFlag|SyncPredFlag);
Yap_InitCPred ("sh", 0, p_sh, SafePredFlag|SyncPredFlag);
/** @pred sh
Creates a new shell interaction.
*/
Yap_InitCPred ("$shell", 1, p_shell, SafePredFlag|SyncPredFlag|UserCPredFlag);
Yap_InitCPred ("system", 1, p_system, SafePredFlag|SyncPredFlag|UserCPredFlag);
Yap_InitCPred ("rename", 2, p_mv, SafePredFlag|SyncPredFlag);
/** @pred rename(+ _F_,+ _G_)
Renames file _F_ to _G_.
*/
Yap_InitCPred ("$yap_home", 1, p_yap_home, SafePredFlag);
Yap_InitCPred ("$yap_paths", 3, p_yap_paths, SafePredFlag);
Yap_InitCPred ("$dir_separator", 1, p_dir_sp, SafePredFlag);

28
C/threads.c Executable file → Normal file
View File

@ -18,6 +18,11 @@
static char SccsId[] = "%W% %G%";
#endif
/**
@ingroup Threads
@{
*/
#include "Yap.h"
#include "Yatom.h"
#include "YapHeap.h"
@ -1070,11 +1075,31 @@ void Yap_InitThreadPreds(void)
Yap_InitCPred("$thread_join", 1, p_thread_join, 0);
Yap_InitCPred("$thread_destroy", 1, p_thread_destroy, 0);
Yap_InitCPred("thread_yield", 0, p_thread_yield, 0);
/** @pred thread_yield
Voluntarily relinquish the processor.
*/
Yap_InitCPred("$detach_thread", 1, p_thread_detach, 0);
Yap_InitCPred("$thread_detached", 1, p_thread_detached, 0);
Yap_InitCPred("$thread_detached", 2, p_thread_detached2, 0);
Yap_InitCPred("$thread_exit", 0, p_thread_exit, 0);
Yap_InitCPred("thread_setconcurrency", 2, p_thread_set_concurrency, 0);
/** @pred thread_setconcurrency(+ _Old_, - _New_)
Determine the concurrency of the process, which is defined as the
maximum number of concurrently active threads. `Active` here means
they are using CPU time. This option is provided if the
thread-implementation provides
`pthread_setconcurrency()`. Solaris is a typical example of this
family. On other systems this predicate unifies _Old_ to 0 (zero)
and succeeds silently.
*/
Yap_InitCPred("$valid_thread", 1, p_valid_thread, 0);
Yap_InitCPred("$new_mutex", 1, p_new_mutex, SafePredFlag);
Yap_InitCPred("$destroy_mutex", 1, p_destroy_mutex, SafePredFlag);
@ -1195,3 +1220,6 @@ void Yap_InitThreadPreds(void)
#endif /* THREADS */
/**
@}
*/

17
C/tracer.c Executable file → Normal file
View File

@ -449,10 +449,27 @@ void
Yap_InitLowLevelTrace(void)
{
Yap_InitCPred("start_low_level_trace", 0, p_start_low_level_trace, SafePredFlag);
/** @pred start_low_level_trace
Begin display of messages at procedure entry and retry.
*/
#if THREADS
Yap_InitCPred("start_low_level_trace", 1, p_start_low_level_trace2, SafePredFlag);
#endif
Yap_InitCPred("stop_low_level_trace", 0, p_stop_low_level_trace, SafePredFlag);
/** @pred stop_low_level_trace
Stop display of messages at procedure entry and retry.
Note that this compile-time option will slow down execution.
*/
Yap_InitCPred("show_low_level_trace", 0, p_show_low_level_trace, SafePredFlag);
Yap_InitCPred("total_choicepoints", 1, p_total_choicepoints, SafePredFlag);
Yap_InitCPred("reset_total_choicepoints", 0, p_reset_total_choicepoints, SafePredFlag);

View File

@ -14,6 +14,35 @@
* comments: Unification and other auxiliary routines for absmi *
* *
*************************************************************************/
/** @defgroup Rational_Trees Rational Trees
@ingroup YAPExtensions
@{
Prolog unification is not a complete implementation. For efficiency
considerations, Prolog systems do not perform occur checks while
unifying terms. As an example, `X = a(X)` will not fail but instead
will create an infinite term of the form `a(a(a(a(a(...)))))`, or
<em>rational tree</em>.
Rational trees are now supported by default in YAP. In previous
versions, this was not the default and these terms could easily lead
to infinite computation. For example, `X = a(X), X = X` would
enter an infinite loop.
The `RATIONAL_TREES` flag improves support for these
terms. Internal primitives are now aware that these terms can exist, and
will not enter infinite loops. Hence, the previous unification will
succeed. Another example, `X = a(X), ground(X)` will succeed
instead of looping. Other affected built-ins include the term comparison
primitives, numbervars/3, copy_term/2, and the internal
data base routines. The support does not extend to Input/Output routines
or to assert/1 YAP does not allow directly reading
rational trees, and you need to use `write_depth/2` to avoid
entering an infinite cycle when trying to write an infinite term.
*/
#define IN_UNIFY_C 1
#define HAS_CACHE_REGS 1
@ -969,7 +998,37 @@ Yap_InitUnify(void)
CACHE_REGS
Term cm = CurrentModule;
Yap_InitCPred("unify_with_occurs_check", 2, p_ocunify, SafePredFlag);
/** @pred unify_with_occurs_check(?T1,?T2) is iso
Obtain the most general unifier of terms _T1_ and _T2_, if there
is one.
This predicate implements the full unification algorithm. An example:n
~~~~~{.prolog}
unify_with_occurs_check(a(X,b,Z),a(X,A,f(B)).
~~~~~
will succeed with the bindings `A = b` and `Z = f(B)`. On the
other hand:
~~~~~{.prolog}
unify_with_occurs_check(a(X,b,Z),a(X,A,f(Z)).
~~~~~
would fail, because `Z` is not unifiable with `f(Z)`. Note that
`(=)/2` would succeed for the previous examples, giving the following
bindings `A = b` and `Z = f(Z)`.
*/
Yap_InitCPred("acyclic_term", 1, p_acyclic, SafePredFlag|TestPredFlag);
/** @pred acyclic_term( _T_) is iso
Succeeds if there are loops in the term _T_, that is, it is an infinite term.
*/
CurrentModule = TERMS_MODULE;
Yap_InitCPred("cyclic_term", 1, p_cyclic, SafePredFlag|TestPredFlag);
Yap_InitCPred("unifiable", 3, p_unifiable, 0);

View File

@ -17,6 +17,9 @@
#ifdef SCCS
static char SccsId[] = "@(#)utilpreds.c 1.3";
#endif
/** @addtogroup YAP_Terms
*/
#include "absmi.h"
#include "YapHeap.h"
@ -5277,22 +5280,119 @@ void Yap_InitUtilCPreds(void)
CACHE_REGS
Term cm = CurrentModule;
Yap_InitCPred("copy_term", 2, p_copy_term, 0);
/** @pred copy_term(? _TI_,- _TF_) is iso
Term _TF_ is a variant of the original term _TI_, such that for
each variable _V_ in the term _TI_ there is a new variable _V'_
in term _TF_. Notice that:
+ suspended goals and attributes for attributed variables in _TI_ are also duplicated;
+ ground terms are shared between the new and the old term.
If you do not want any sharing to occur please use
duplicate_term/2.
*/
Yap_InitCPred("duplicate_term", 2, p_duplicate_term, 0);
/** @pred duplicate_term(? _TI_,- _TF_)
Term _TF_ is a variant of the original term _TI_, such that
for each variable _V_ in the term _TI_ there is a new variable
_V'_ in term _TF_, and the two terms do not share any
structure. All suspended goals and attributes for attributed variables
in _TI_ are also duplicated.
Also refer to copy_term/2.
*/
Yap_InitCPred("copy_term_nat", 2, p_copy_term_no_delays, 0);
/** @pred copy_term_nat(? _TI_,- _TF_)
As copy_term/2. Attributes however, are <em>not</em> copied but replaced
by fresh variables.
*/
Yap_InitCPred("ground", 1, p_ground, SafePredFlag);
/** @pred ground( _T_) is iso
Succeeds if there are no free variables in the term _T_.
*/
Yap_InitCPred("$variables_in_term", 3, p_variables_in_term, 0);
Yap_InitCPred("$free_variables_in_term", 3, p_free_variables_in_term, 0);
Yap_InitCPred("$non_singletons_in_term", 3, p_non_singletons_in_term, 0);
Yap_InitCPred("term_variables", 2, p_term_variables, 0);
/** @pred term_variables(? _Term_, - _Variables_) is iso
Unify _Variables_ with the list of all variables of term
_Term_. The variables occur in the order of their first
appearance when traversing the term depth-first, left-to-right.
*/
Yap_InitCPred("term_variables", 3, p_term_variables3, 0);
Yap_InitCPred("term_attvars", 2, p_term_attvars, 0);
/** @pred term_attvars(+ _Term_,- _AttVars_)
_AttVars_ is a list of all attributed variables in _Term_ and
its attributes. I.e., term_attvars/2 works recursively through
attributes. This predicate is Cycle-safe.
*/
Yap_InitCPred("is_list", 1, p_is_list, SafePredFlag|TestPredFlag);
Yap_InitCPred("$is_list_or_partial_list", 1, p_is_list_or_partial_list, SafePredFlag|TestPredFlag);
Yap_InitCPred("rational_term_to_tree", 4, p_break_rational, 0);
/** @pred rational_term_to_tree(? _TI_,- _TF_, ?SubTerms, ?MoreSubterms)
The term _TF_ is a forest representation (without cycles and repeated
terms) for the Prolog term _TI_. The term _TF_ is the main term. The
difference list _SubTerms_-_MoreSubterms_ stores terms of the form
_V=T_, where _V_ is a new variable occuring in _TF_, and _T_ is a copy
of a sub-term from _TI_.
*/
Yap_InitCPred("term_factorized", 3, p_break_rational3, 0);
/** @pred term_factorized(? _TI_,- _TF_, ?SubTerms)
Similar to rational_term_to_tree/4, but _SubTerms_ is a proper list.
*/
Yap_InitCPred("=@=", 2, p_variant, 0);
Yap_InitCPred("numbervars", 3, p_numbervars, 0);
/** @pred numbervars( _T_,+ _N1_,- _Nn_)
Instantiates each variable in term _T_ to a term of the form:
`$VAR( _I_)`, with _I_ increasing from _N1_ to _Nn_.
*/
Yap_InitCPred("unnumbervars", 2, p_unnumbervars, 0);
/** @pred unnumbervars( _T_,+ _NT_)
Replace every `$VAR( _I_)` by a free variable.
*/
/* use this carefully */
Yap_InitCPred("$skip_list", 3, p_skip_list, SafePredFlag|TestPredFlag);
Yap_InitCPred("$skip_list", 4, p_skip_list4, SafePredFlag|TestPredFlag);

View File

@ -5,7 +5,7 @@
*
* @defgroup yap-cplus-interface An object oriented interface for YAP.
*
*
* @ingroup ChYInterface
* @tableofcontents
*
*

View File

@ -13,6 +13,19 @@
* version: $Id: TermExt.h,v 1.15 2008-03-25 22:03:13 vsc Exp $ *
*************************************************************************/
/**
@file TermExt.h
@page Extensions Extensions to Prolog
YAP includes a number of extensions over the original Prolog
language. Next, we discuss support to the most important ones.
*/
#ifdef USE_SYSTEM_MALLOC
#define SF_STORE (&(Yap_heap_regs->funcs))
#else

View File

@ -19,6 +19,16 @@
@defgroup arithmetic Arithmetic in YAP
@ingroup YAPBuiltins
+ See @ref arithmetic_preds for the predicates that implement arithment
+ See @ref arithmetic_cmps for the arithmetic comparisons supported in YAP
+ See @ref arithmetic_operators for how to call arithmetic operations in YAP
@tableofcontents
YAP supports several different numeric types:

View File

@ -208,6 +208,14 @@ void Yap_init_optyap_preds(void) {
Yap_InitCPred("$c_tabling_mode", 3, p_tabling_mode, SafePredFlag|SyncPredFlag);
Yap_InitCPred("$c_abolish_table", 2, p_abolish_table, SafePredFlag|SyncPredFlag);
Yap_InitCPred("abolish_all_tables", 0, p_abolish_all_tables, SafePredFlag|SyncPredFlag);
/** @pred abolish_all_tables/0
Removes all the entries from the table space for all tabled
predicates. The predicates remain as tabled predicates.
*/
Yap_InitCPred("show_tabled_predicates", 1, p_show_tabled_predicates, SafePredFlag|SyncPredFlag);
Yap_InitCPred("$c_show_table", 3, p_show_table, SafePredFlag|SyncPredFlag);
Yap_InitCPred("show_all_tables", 1, p_show_all_tables, SafePredFlag|SyncPredFlag);

View File

@ -11,6 +11,49 @@
** **
************************************************************************/
/**
@defgroup Parallelism Parallelism in YAP
@ingroup YAPExtensions
@{
There has been a sizeable amount of work on an or-parallel
implementation for YAP, called *YAPOr*. Most of this work has
been performed by Ricardo Rocha. In this system parallelism is exploited
implicitly by running several alternatives in or-parallel. This option
can be enabled from the `configure` script or by checking the
system's `Makefile`.
*YAPOr* is still a very experimental system, going through rapid
development. The following restrictions are of note:
+ *YAPOr* currently only supports the Linux/X86 and SPARC/Solaris
platforms. Porting to other Unix-like platforms should be straightforward.
+ *YAPOr* does not support parallel updates to the
data-base.
+ *YAPOr* does not support opening or closing of streams during
parallel execution.
+ Garbage collection and stack shifting are not supported in
*YAPOr*.
+ Built-ins that cause side-effects can only be executed when
left-most in the search-tree. There are no primitives to provide
asynchronous or cavalier execution of these built-ins, as in Aurora or
Muse.
+ YAP does not support voluntary suspension of work.
We expect that some of these restrictions will be removed in future
releases.
*/
/* ------------------------- **
** Struct or_frame **
** ------------------------- */

View File

@ -58,7 +58,7 @@ PROJECT_LOGO = misc/icons/yap_96x96x32.png
# entered, it will be relative to the location where doxygen was started. If
# left blank the current directory will be used.
OUTPUT_DIRECTORY = doxout
OUTPUT_DIRECTORY = ../doxout
# If the CREATE_SUBDIRS tag is set to YES, then doxygen will create 4096 sub-
# directories (in 2 levels) under the output directory of each output format and
@ -786,8 +786,7 @@ WARN_LOGFILE =
# INPUT = /Users/vsc/git/yap-6.3/packages/cplint/mcintyre.pl
#INPUT = /Users/vsc/git/yap-6.3/packages/R/R.pl
INPUT = docs/yap.md \
docs/yapdocs.yap \
INPUT = foreigns.yap docs/yap.md docs/chr.md docs/threads.md docs/syntax.md docs/clpqr.md \
pl \
C \
H \
@ -796,8 +795,8 @@ INPUT = docs/yap.md \
packages \
library \
CXX \
OPTYap \
docs/foreigns.yap
OPTYap
# This tag can be used to specify the character encoding of the source files
# that doxygen parses. Internally doxygen uses the UTF-8 encoding. Doxygen uses
@ -877,7 +876,9 @@ RECURSIVE = YES
# Note that relative paths are relative to the directory from which doxygen is
# run.
EXCLUDE = *pltotex.pl packages/swig/android
EXCLUDE = *pltotex.pl packages/swig/android \
paackages/chr \
packages/RDF
# The EXCLUDE_SYMLINKS tag can be used to select whether or not files or
# directories that are symbolic links (a Unix file system feature) are excluded

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -14,6 +14,12 @@
* *
*************************************************************************/
/**
@file YapInterface.h
*/
#ifndef _yap_c_interface_h
@ -36,6 +42,7 @@
/**
@defgroup c-interface YAP original C-interface
@Ingroup ChYInterface
Before describing in full detail how to interface to C code, we will examine
a brief example.
@ -1328,7 +1335,8 @@ arguments to the backtrackable procedure.
@section YAPLibrary Using YAP as a Library
@defgroup YAPAsLibrary Using YAP as a Library
@subgroup c-interface
YAP can be used as a library to be called from other
programs. To do so, you must first create the YAP library:

View File

@ -1,3 +1,13 @@
/** @defgroup Apply Apply Macros
@ingroup YAPLibrary
@{
This library provides a SWI-compatible set of utilities for applying a
predicate to all elements of a list. The library just forwards
definitions from the `maplist` library.
*/
:- module(apply,[]).
@ -12,3 +22,7 @@
partition/5
]).
/**
@}
*/

View File

@ -1,6 +1,6 @@
% This file has been included as an YAP library by Vitor Santos Costa, 2008
% it is based on the arg library from Quintus Prolog
% it is based on the Quintus Prolog arg library
:- module(arg,
[
@ -13,6 +13,8 @@
path_arg/3
]).
arg0(0,T,A) :- !,
functor(T,A,_).
arg0(I,T,A) :-

View File

@ -4,6 +4,175 @@
% Note : the keys should be bound, the associated values need not be.
/** @defgroup Association_Lists Association Lists
@ingroup YAPLibrary
@{
The following association list manipulation predicates are available
once included with the `use_module(library(assoc))` command. The
original library used Richard O'Keefe's implementation, on top of
unbalanced binary trees. The current code utilises code from the
red-black trees library and emulates the SICStus Prolog interface.
*/
/** @pred assoc_to_list(+ _Assoc_,? _List_)
Given an association list _Assoc_ unify _List_ with a list of
the form _Key-Val_, where the elements _Key_ are in ascending
order.
*/
/** @pred del_assoc(+ _Key_, + _Assoc_, ? _Val_, ? _NewAssoc_)
Succeeds if _NewAssoc_ is an association list, obtained by removing
the element with _Key_ and _Val_ from the list _Assoc_.
*/
/** @pred del_max_assoc(+ _Assoc_, ? _Key_, ? _Val_, ? _NewAssoc_)
Succeeds if _NewAssoc_ is an association list, obtained by removing
the largest element of the list, with _Key_ and _Val_ from the
list _Assoc_.
*/
/** @pred del_min_assoc(+ _Assoc_, ? _Key_, ? _Val_, ? _NewAssoc_)
Succeeds if _NewAssoc_ is an association list, obtained by removing
the smallest element of the list, with _Key_ and _Val_
from the list _Assoc_.
*/
/** @pred empty_assoc(+ _Assoc_)
Succeeds if association list _Assoc_ is empty.
*/
/** @pred gen_assoc(+ _Assoc_,? _Key_,? _Value_)
Given the association list _Assoc_, unify _Key_ and _Value_
with two associated elements. It can be used to enumerate all elements
in the association list.
*/
/** @pred get_assoc(+ _Key_,+ _Assoc_,? _Value_)
If _Key_ is one of the elements in the association list _Assoc_,
return the associated value.
*/
/** @pred get_assoc(+ _Key_,+ _Assoc_,? _Value_,+ _NAssoc_,? _NValue_)
If _Key_ is one of the elements in the association list _Assoc_,
return the associated value _Value_ and a new association list
_NAssoc_ where _Key_ is associated with _NValue_.
*/
/** @pred get_next_assoc(+ _Key_,+ _Assoc_,? _Next_,? _Value_)
If _Key_ is one of the elements in the association list _Assoc_,
return the next key, _Next_, and its value, _Value_.
*/
/** @pred get_prev_assoc(+ _Key_,+ _Assoc_,? _Next_,? _Value_)
If _Key_ is one of the elements in the association list _Assoc_,
return the previous key, _Next_, and its value, _Value_.
*/
/** @pred is_assoc(+ _Assoc_)
Succeeds if _Assoc_ is an association list, that is, if it is a
red-black tree.
*/
/** @pred list_to_assoc(+ _List_,? _Assoc_)
Given a list _List_ such that each element of _List_ is of the
form _Key-Val_, and all the _Keys_ are unique, _Assoc_ is
the corresponding association list.
*/
/** @pred map_assoc(+ _Pred_,+ _Assoc_)
Succeeds if the unary predicate name _Pred_( _Val_) holds for every
element in the association list.
*/
/** @pred map_assoc(+ _Pred_,+ _Assoc_,? _New_)
Given the binary predicate name _Pred_ and the association list
_Assoc_, _New_ in an association list with keys in _Assoc_,
and such that if _Key-Val_ is in _Assoc_, and _Key-Ans_ is in
_New_, then _Pred_( _Val_, _Ans_) holds.
*/
/** @pred max_assoc(+ _Assoc_,- _Key_,? _Value_)
Given the association list
_Assoc_, _Key_ in the largest key in the list, and _Value_
the associated value.
*/
/** @pred min_assoc(+ _Assoc_,- _Key_,? _Value_)
Given the association list
_Assoc_, _Key_ in the smallest key in the list, and _Value_
the associated value.
*/
/** @pred ord_list_to_assoc(+ _List_,? _Assoc_)
Given an ordered list _List_ such that each element of _List_ is
of the form _Key-Val_, and all the _Keys_ are unique, _Assoc_ is
the corresponding association list.
*/
/** @pred put_assoc(+ _Key_,+ _Assoc_,+ _Val_,+ _New_)
The association list _New_ includes and element of association
_key_ with _Val_, and all elements of _Assoc_ that did not
have key _Key_.
*/
:- module(assoc, [
empty_assoc/1,
assoc_to_list/2,
@ -129,3 +298,6 @@ assoc_to_keys(T, Ks) :-
rb_keys(T, Ks).
/**
@}
*/

View File

@ -17,6 +17,261 @@
:- module(attributes, [op(1150, fx, attribute)]).
/** @defgroup Old_Style_Attribute_Declarations SICStus Prolog style Attribute Declarations
@ingroup Attributed_Variables
@{
Old style attribute declarations are activated through loading the library <tt>atts</tt> . The command
~~~~~
| ?- use_module(library(atts)).
~~~~~
enables this form of use of attributed variables. The package provides the
following functionality:
+ Each attribute must be declared first. Attributes are described by a functor
and are declared per module. Each Prolog module declares its own sets of
attributes. Different modules may have different functors with the same
module.
+ The built-in put_atts/2 adds or deletes attributes to a
variable. The variable may be unbound or may be an attributed
variable. In the latter case, YAP discards previous values for the
attributes.
+ The built-in get_atts/2 can be used to check the values of
an attribute associated with a variable.
+ The unification algorithm calls the user-defined predicate
<tt>verify_attributes/3</tt> before trying to bind an attributed
variable. Unification will resume after this call.
+ The user-defined predicate
<tt>attribute_goal/2</tt> converts from an attribute to a goal.
+ The user-defined predicate
<tt>project_attributes/2</tt> is used from a set of variables into a set of
constraints or goals. One application of <tt>project_attributes/2</tt> is in
the top-level, where it is used to output the set of
floundered constraints at the end of a query.
/** @defgroup Attribute_Declarations Attribute Declarations
@ingroup Old_Style_Attribute_Declarations
@{
Attributes are compound terms associated with a variable. Each attribute
has a <em>name</em> which is <em>private</em> to the module in which the
attribute was defined. Variables may have at most one attribute with a
name. Attribute names are defined with the following declaration:
~~~~~
:- attribute AttributeSpec, ..., AttributeSpec.
~~~~~
where each _AttributeSpec_ has the form ( _Name_/ _Arity_).
One single such declaration is allowed per module _Module_.
Although the YAP module system is predicate based, attributes are local
to modules. This is implemented by rewriting all calls to the
built-ins that manipulate attributes so that attribute names are
preprocessed depending on the module. The `user:goal_expansion/3`
mechanism is used for this purpose.
The attribute manipulation predicates always work as follows:
+ The first argument is the unbound variable associated with
attributes,
+ The second argument is a list of attributes. Each attribute will
be a Prolog term or a constant, prefixed with the <tt>+</tt> and <tt>-</tt> unary
operators. The prefix <tt>+</tt> may be dropped for convenience.
The following three procedures are available to the user. Notice that
these built-ins are rewritten by the system into internal built-ins, and
that the rewriting process <em>depends</em> on the module on which the
built-ins have been invoked.
The user-predicate predicate verify_attributes/3 is called when
attempting to unify an attributed variable which might have attributes
in some _Module_.
Attributes are usually presented as goals. The following routines are
used by built-in predicates such as call_residue/2 and by the
Prolog top-level to display attributes:
Constraint solvers must be able to project a set of constraints to a set
of variables. This is useful when displaying the solution to a goal, but
may also be used to manipulate computations. The user-defined
project_attributes/2 is responsible for implementing this
projection.
The following two examples example is taken from the SICStus Prolog manual. It
sketches the implementation of a simple finite domain `solver`. Note
that an industrial strength solver would have to provide a wider range
of functionality and that it quite likely would utilize a more efficient
representation for the domains proper. The module exports a single
predicate `domain( _-Var_, _?Domain_)` which associates
_Domain_ (a list of terms) with _Var_. A variable can be
queried for its domain by leaving _Domain_ unbound.
We do not present here a definition for project_attributes/2.
Projecting finite domain constraints happens to be difficult.
~~~~~
:- module(domain, [domain/2]).
:- use_module(library(atts)).
:- use_module(library(ordsets), [
ord_intersection/3,
ord_intersect/2,
list_to_ord_set/2
]).
:- attribute dom/1.
verify_attributes(Var, Other, Goals) :-
get_atts(Var, dom(Da)), !, % are we involved?
( var(Other) -> % must be attributed then
( get_atts(Other, dom(Db)) -> % has a domain?
ord_intersection(Da, Db, Dc),
Dc = [El|Els], % at least one element
( Els = [] -> % exactly one element
Goals = [Other=El] % implied binding
; Goals = [],
put_atts(Other, dom(Dc))% rescue intersection
)
; Goals = [],
put_atts(Other, dom(Da)) % rescue the domain
)
; Goals = [],
ord_intersect([Other], Da) % value in domain?
).
verify_attributes(_, _, []). % unification triggered
% because of attributes
% in other modules
attribute_goal(Var, domain(Var,Dom)) :- % interpretation as goal
get_atts(Var, dom(Dom)).
domain(X, Dom) :-
var(Dom), !,
get_atts(X, dom(Dom)).
domain(X, List) :-
list_to_ord_set(List, Set),
Set = [El|Els], % at least one element
( Els = [] -> % exactly one element
X = El % implied binding
; put_atts(Fresh, dom(Set)),
X = Fresh % may call
% verify_attributes/3
).
~~~~~
Note that the _implied binding_ `Other=El` was deferred until after
the completion of `verify_attribute/3`. Otherwise, there might be a
danger of recursively invoking `verify_attribute/3`, which might bind
`Var`, which is not allowed inside the scope of `verify_attribute/3`.
Deferring unifications into the third argument of `verify_attribute/3`
effectively serializes the calls to `verify_attribute/3`.
Assuming that the code resides in the file domain.yap, we
can use it via:
~~~~~
| ?- use_module(domain).
~~~~~
Let's test it:
~~~~~
| ?- domain(X,[5,6,7,1]), domain(Y,[3,4,5,6]), domain(Z,[1,6,7,8]).
domain(X,[1,5,6,7]),
domain(Y,[3,4,5,6]),
domain(Z,[1,6,7,8]) ?
yes
| ?- domain(X,[5,6,7,1]), domain(Y,[3,4,5,6]), domain(Z,[1,6,7,8]),
X=Y.
Y = X,
domain(X,[5,6]),
domain(Z,[1,6,7,8]) ?
yes
| ?- domain(X,[5,6,7,1]), domain(Y,[3,4,5,6]), domain(Z,[1,6,7,8]),
X=Y, Y=Z.
X = 6,
Y = 6,
Z = 6
~~~~~
To demonstrate the use of the _Goals_ argument of
verify_attributes/3, we give an implementation of
freeze/2. We have to name it `myfreeze/2` in order to
avoid a name clash with the built-in predicate of the same name.
~~~~~
:- module(myfreeze, [myfreeze/2]).
:- use_module(library(atts)).
:- attribute frozen/1.
verify_attributes(Var, Other, Goals) :-
get_atts(Var, frozen(Fa)), !, % are we involved?
( var(Other) -> % must be attributed then
( get_atts(Other, frozen(Fb)) % has a pending goal?
-> put_atts(Other, frozen((Fa,Fb))) % rescue conjunction
; put_atts(Other, frozen(Fa)) % rescue the pending goal
),
Goals = []
; Goals = [Fa]
).
verify_attributes(_, _, []).
attribute_goal(Var, Goal) :- % interpretation as goal
get_atts(Var, frozen(Goal)).
myfreeze(X, Goal) :-
put_atts(Fresh, frozen(Goal)),
Fresh = X.
~~~~~
Assuming that this code lives in file myfreeze.yap,
we would use it via:
~~~~~
| ?- use_module(myfreeze).
| ?- myfreeze(X,print(bound(x,X))), X=2.
bound(x,2) % side effect
X = 2 % bindings
~~~~~
The two solvers even work together:
~~~~~
| ?- myfreeze(X,print(bound(x,X))), domain(X,[1,2,3]),
domain(Y,[2,10]), X=Y.
bound(x,2) % side effect
X = 2, % bindings
Y = 2
~~~~~
The two example solvers interact via bindings to shared attributed
variables only. More complicated interactions are likely to be found
in more sophisticated solvers. The corresponding
verify_attributes/3 predicates would typically refer to the
attributes from other known solvers/modules via the module prefix in
` _Module_:get_atts/2`.
*/
:- use_module(library(lists), [member/2]).
:- multifile
@ -65,8 +320,42 @@ store_new_module(Mod,Ar,ArgPosition) :-
:- user_defined_directive(attribute(G), attributes:new_attribute(G)).
/** @pred _Module_:get_atts( _-Var_, _?ListOfAttributes_)
Unify the list _?ListOfAttributes_ with the attributes for the unbound
variable _Var_. Each member of the list must be a bound term of the
form `+( _Attribute_)`, `-( _Attribute_)` (the <tt>kbd</tt>
prefix may be dropped). The meaning of <tt>+</tt> and <tt>-</tt> is:
+ +( _Attribute_)
Unifies _Attribute_ with a corresponding attribute associated with
_Var_, fails otherwise.
+ -( _Attribute_)
Succeeds if a corresponding attribute is not associated with
_Var_. The arguments of _Attribute_ are ignored.
*/
user:goal_expansion(get_atts(Var,AccessSpec), Mod, Goal) :-
expand_get_attributes(AccessSpec,Mod,Var,Goal).
/** @pred _Module_:put_atts( _-Var_, _?ListOfAttributes_)
Associate with or remove attributes from a variable _Var_. The
attributes are given in _?ListOfAttributes_, and the action depends
on how they are prefixed:
+ +( _Attribute_)
Associate _Var_ with _Attribute_. A previous value for the
attribute is simply replace (like with `set_mutable/2`).
+ -( _Attribute_)
Remove the attribute with the same name. If no such attribute existed,
simply succeed.
*/
user:goal_expansion(put_atts(Var,AccessSpec), Mod, Goal) :-
expand_put_attributes(AccessSpec, Mod, Var, Goal).
@ -177,6 +466,28 @@ find_used([M|Mods],Mods0,L0,Lf) :-
find_used([_|Mods],Mods0,L0,Lf) :-
find_used(Mods,Mods0,L0,Lf).
/** @pred _Module_:verify_attributes( _-Var_, _+Value_, _-Goals_)
The predicate is called when trying to unify the attributed variable
_Var_ with the Prolog term _Value_. Note that _Value_ may be
itself an attributed variable, or may contain attributed variables. The
goal <tt>verify_attributes/3</tt> is actually called before _Var_ is
unified with _Value_.
It is up to the user to define which actions may be performed by
<tt>verify_attributes/3</tt> but the procedure is expected to return in
_Goals_ a list of goals to be called <em>after</em> _Var_ is
unified with _Value_. If <tt>verify_attributes/3</tt> fails, the
unification will fail.
Notice that the <tt>verify_attributes/3</tt> may be called even if _Var_<
has no attributes in module <tt>Module</tt>. In this case the routine should
simply succeed with _Goals_ unified with the empty list.
*/
do_verify_attributes([], _, _, []).
do_verify_attributes([Mod|Mods], AttVar, Binding, [Mod:Goal|Goals]) :-
current_predicate(verify_attributes,Mod:verify_attributes(_,_,_)), !,
@ -185,5 +496,6 @@ do_verify_attributes([Mod|Mods], AttVar, Binding, [Mod:Goal|Goals]) :-
do_verify_attributes([_|Mods], AttVar, Binding, Goals) :-
do_verify_attributes(Mods, AttVar, Binding, Goals).
/**
@}
*/

View File

@ -15,6 +15,51 @@
* *
*************************************************************************/
/** @defgroup AVL_Trees AVL Trees
@ingroup YAPLibrary
@{
AVL trees are balanced search binary trees. They are named after their
inventors, Adelson-Velskii and Landis, and they were the first
dynamically balanced trees to be proposed. The YAP AVL tree manipulation
predicates library uses code originally written by Martin van Emdem and
published in the Logic Programming Newsletter, Autumn 1981. A bug in
this code was fixed by Philip Vasey, in the Logic Programming
Newsletter, Summer 1982. The library currently only includes routines to
insert and lookup elements in the tree. Please try red-black trees if
you need deletion.
*/
/** @pred avl_insert(+ _Key_,? _Value_,+ _T0_,- _TF_)
Add an element with key _Key_ and _Value_ to the AVL tree
_T0_ creating a new AVL tree _TF_. Duplicated elements are
allowed.
*/
/** @pred avl_lookup(+ _Key_,- _Value_,+ _T_)
Lookup an element with key _Key_ in the AVL tree
_T_, returning the value _Value_.
*/
/** @pred avl_new(+ _T_)
Create a new tree.
*/
:- module(avl, [
avl_new/1,
avl_insert/4,
@ -81,3 +126,7 @@ avl_lookup(<, Value, L, _, Key, _) :-
avl_lookup(>, Value, _, R, Key, _) :-
avl_lookup(Key, Value, R).
/**
@}
*/

View File

@ -2,6 +2,10 @@
/*
@defgroup YapHash Backtrackable Hash Tables
@ingroup YapLibrary
@{
This code implements hash-arrays.
It requires the hash key to be a ground term.
@ -35,27 +39,52 @@ It relies on dynamic array code.
array_default_size(2048).
/** is_b_hash( +Hash )
Term _Hash_ is a hash table.
*/
is_b_hash(V) :- var(V), !, fail.
is_b_hash(hash(_,_,_,_,_)).
/** b_hash_new( -NewHash )
Create a empty hash table _NewHash_, with size 2048 entries.
*/
b_hash_new(hash(Keys, Vals, Size, N, _, _)) :-
array_default_size(Size),
array(Keys, Size),
array(Vals, Size),
create_mutable(0, N).
/** b_hash_new( -_NewHash_, +_Size_ )
Create a empty hash table, with size _Size_ entries.
*/
b_hash_new(hash(Keys, Vals, Size, N, _, _), Size) :-
array(Keys, Size),
array(Vals, Size),
create_mutable(0, N).
/** b_hash_new( -_NewHash_, +_Size_, :_Hash_, :_Cmp_ )
Create a empty hash table, with size _Size_ entries.
_Hash_ defines a partition function, and _Cmp_ defined a comparison function.
*/
b_hash_new(hash(Keys,Vals, Size, N, HashF, CmpF), Size, HashF, CmpF) :-
array(Keys, Size),
array(Vals, Size),
create_mutable(0, N).
/** b_hash_size( +_Hash_, -_Size_ )
_Size_ unifies with the size of the hash table _Hash_.
*/
b_hash_size(hash(_, _, Size, _, _, _), Size).
/** b_hash_size_lookup( +_Key_, ?_Val_, +_Hash_ )
Search the ground term _Key_ in table _Hash_ and unify _Val_ with the associated entry.
*/
b_hash_lookup(Key, Val, hash(Keys, Vals, Size, _, F, CmpF)):-
hash_f(Key, Size, Index, F),
fetch_key(Keys, Index, Size, Key, CmpF, ActualIndex),
@ -74,6 +103,10 @@ fetch_key(Keys, Index, Size, Key, CmpF, ActualIndex) :-
fetch_key(Keys, I1, Size, Key, CmpF, ActualIndex)
).
/** b_hash_size_lookup( +_Key_, +_Hash_, +NewVal )
Update to the value associated with the ground term _Key_ in table _Hash_ to _NewVal_.
*/
b_hash_update(Hash, Key, NewVal):-
Hash = hash(Keys, Vals, Size, _, F, CmpF),
hash_f(Key,Size,Index,F),
@ -81,7 +114,11 @@ b_hash_update(Hash, Key, NewVal):-
array_element(Vals, ActualIndex, Mutable),
update_mutable(NewVal, Mutable).
b_hash_update(Hash, Key, OldVal, NewVal):-
/** b_hash_size_lookup( +_Key_, -_OldVal_, +_Hash_, +NewVal )
Update to the value associated with the ground term _Key_ in table _Hash_ to _NewVal_, and unify _OldVal_ with the current value.
*/
b_hash_update(Hash, Key, OldVal, NewVal):-§
Hash = hash(Keys, Vals, Size, _, F, CmpF),
hash_f(Key,Size,Index,F),
fetch_key(Keys, Index, Size, Key, CmpF, ActualIndex),
@ -89,6 +126,10 @@ b_hash_update(Hash, Key, OldVal, NewVal):-
get_mutable(OldVal, Mutable),
update_mutable(NewVal, Mutable).
/** b_hash_insert(+_Hash_, +_Key_, _Val_, +_NewHash_ )
Insert the term _Key_-_Val_ in table _Hash_ and unify _NewHash_ with the result. If ground term _Key_ exists, update the dictionary.
*/
b_hash_insert(Hash, Key, NewVal, NewHash):-
Hash = hash(Keys, Vals, Size, N, F, CmpF),
hash_f(Key,Size,Index,F),
@ -112,6 +153,10 @@ find_or_insert(Keys, Index, Size, N, CmpF, Vals, Key, NewVal, Hash, NewHash) :-
find_or_insert(Keys, I1, Size, N, CmpF, Vals, Key, NewVal, Hash, NewHash)
).
/** b_hash_insert_new(+_Hash_, +_Key_, _Val_, +_NewHash_ )
Insert the term _Key_-_Val_ in table _Hash_ and unify _NewHash_ with the result. If ground term _Key_ exists, fail.
*/
b_hash_insert_new(Hash, Key, NewVal, NewHash):-
Hash = hash(Keys, Vals, Size, N, F, CmpF),
hash_f(Key,Size,Index,F),
@ -214,15 +259,27 @@ cmp_f(F, A, B) :-
cmp_f(F, A, B) :-
call(F, A, B).
/** b_hash_to_list(+_Hash_, -_KeyValList_ )
The term _KeyValList_ unifies with a list containing all terms _Key_-_Val_ in the hash table.
*/
b_hash_to_list(hash(Keys, Vals, _, _, _, _), LKeyVals) :-
Keys =.. (_.LKs),
Vals =.. (_.LVs),
mklistpairs(LKs, LVs, LKeyVals).
/** b_key_to_list(+_Hash_, -_KeyList_ )
The term _KeyList_ unifies with a list containing all keys in the hash table.
*/
b_hash_keys_to_list(hash(Keys, _, _, _, _, _), LKeys) :-
Keys =.. (_.LKs),
mklistels(LKs, LKeys).
/** b_key_to_list(+_Hash_, -_ValList_ )
The term _`valList_ unifies with a list containing all values in the hash table.
*/
b_hash_values_to_list(hash(_, Vals, _, _, _, _), LVals) :-
Vals =.. (_.LVs),
mklistvals(LVs, LVals).
@ -247,4 +304,6 @@ mklistvals(K.Vals, KK.NVals) :-
get_mutable(KK, K),
mklistvals(Vals, NVals).
/**
@}
*/

View File

@ -201,6 +201,17 @@
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
/** @defgroup Block_Diagram Block Diagram
@ingroup YAPLibrary
@{
This library provides a way of visualizing a prolog program using
modules with blocks. To use it use:
`:-use_module(library(block_diagram))`.
*/
:- module(block_diagram, [make_diagram/2, make_diagram/5]).
/* ---------------------------------------------------------------------- *\
@ -220,6 +231,17 @@
parameter(texts((+inf))).
parameter(depth((+inf))).
parameter(default_ext('.yap')).
/** @pred make_diagram(+inputfilename, +ouputfilename)
This will crawl the files following the use_module, ensure_loaded directives withing the inputfilename.
The result will be a file in dot format.
You can make a pdf at the shell by asking `dot -Tpdf filename > output.pdf`.
*/
make_diagram(InputFile, OutputFile):-
tell(OutputFile),
write('digraph G {\nrankdir=BT'), nl,
@ -229,6 +251,13 @@ make_diagram(InputFile, OutputFile):-
write_explicit,
write('}'), nl,
told.
/** @pred make_diagram(+inputfilename, +ouputfilename, +predicate, +depth, +extension)
The same as make_diagram/2 but you can define how many of the imported/exporeted predicates will be shown with predicate, and how deep the crawler is allowed to go with depth. The extension is used if the file use module directives do not include a file extension.
*/
make_diagram(InputFile, OutputFile, Texts, Depth, Ext):-
integer(Texts),
integer(Depth),
@ -355,6 +384,15 @@ read_module_file(File, Module):-
close(S), working_directory(_,CurDir), !.
read_module_file(_, _).
/** @pred process(+ _StreamInp_, + _Goal_)
For every line _LineIn_ in stream _StreamInp_, call
`call(Goal,LineIn)`.
*/
process(_, end_of_file):-!.
process(_, Term):-
parse_module_directive(Term, box), !, fail.

View File

@ -210,19 +210,14 @@
timer_elapsed/2,
timer_pause/2]).
% set_alarm(+Seconds, +Execute, -ID)
% calls Executes after a time interval of Seconds
% ID is returned to be able to unset the alarm (the call will not be executed)
% set_alarm/3 supports multiple & nested settings of alarms.
% Known Bug: There is the case that an alarm might trigger +-1 second of the set time.
%
% unset_alarm(+ID)
% It will unschedule the alarm.
% It will not affect other concurrent alarms.
%
% time_out_call(+Seconds, +Goal, -Return)
% It will will execute the closure Goal and returns its success or failure at Return.
% If the goal times out in Seconds then Return = timeout.
/** @defgroup CAlarms Concurrent Alarms
@ingroup YAPLibrary
@{
This library provides a concurrent signals. To use it use:
`:-use_module(library(c_alarms))`.
*/
:- use_module(library(lists), [member/2, memberchk/2, delete/3]).
:- use_module(library(ordsets), [ord_add_element/3]).
@ -250,6 +245,14 @@ set_alarm(Seconds, Execute, ID):-
get_next_identity(ID), !,
bb_put(alarms, [alarm(Seconds, ID, Execute)]),
alarm(Seconds, alarm_handler, _).
%% set_alarm(+Seconds, +Execute, -ID)
%
% calls Executes after a time interval of Seconds
% ID is returned to be able to unset the alarm (the call will not be executed)
% set_alarm/3 supports multiple & nested settings of alarms.
% Known Bug: There is the case that an alarm might trigger +-1 second of the set time.
%
set_alarm(Seconds, Execute, ID):-
get_next_identity(ID), !,
bb_get(alarms, [alarm(CurrentSeconds, CurrentID, CurrentExecute)|Alarms]),
@ -265,6 +268,11 @@ set_alarm(Seconds, Execute, ID):-
subtract(Elapsed, alarm(Seconds, ID, Execute), alarm(NewSeconds, ID, Execute)):-
NewSeconds is Seconds - Elapsed.
%% unset_alarm(+ID)
%
% It will unschedule the alarm.
% It will not affect other concurrent alarms.
%
unset_alarm(ID):-
\+ ground(ID),
throw(error(instantiation_error, 'Alarm ID needs to be instantiated.')).
@ -319,6 +327,10 @@ execute([alarm(_, _, Execute)|R]):-
call(Execute),
execute(R).
%% time_out_call(+Seconds, +Goal, -Return)
%
% It will will execute the closure Goal and returns its success or failure at Return.
% If the goal times out in Seconds then Return = timeout.
time_out_call_once(Seconds, Goal, Return):-
bb_get(identity, ID),
set_alarm(Seconds, throw(timeout(ID)), ID),
@ -395,3 +407,7 @@ timer_pause(Name, Elapsed):-
statistics(walltime, [EndTime, _]),
Elapsed is EndTime - StartTime,
assertz('$timer'(Name, paused, Elapsed)).
/**
@}
*/

View File

@ -32,32 +32,81 @@
term_to_atom/2
]).
/** @defgrou CharsIO Operations on Sequences of Codes.
@ingroup YAPLibrary
Term to sequence of codes conversion, mostly replaced by engine code.
*/
:- meta_predicate(with_output_to_chars(0,?)).
:- meta_predicate(with_output_to_chars(0,-,?)).
:- meta_predicate(with_output_to_chars(0,-,?,?)).
/** @pred format_to_chars(+ _Form_, + _Args_, - _Result_)
Execute the built-in procedure format/2 with form _Form_ and
arguments _Args_ outputting the result to the string of character
codes _Result_.
*/
format_to_chars(Format, Args, Codes) :-
format(codes(Codes), Format, Args).
/** @pred format_to_chars(+ _Form_, + _Args_, - _Result_, - _Result0_)
Execute the built-in procedure format/2 with form _Form_ and
arguments _Args_ outputting the result to the difference list of
character codes _Result-Result0_.
*/
format_to_chars(Format, Args, OUT, L0) :-
format(codes(OUT, L0), Format, Args).
/** @pred write_to_chars(+ _Term_, - _Result_)
Execute the built-in procedure write/1 with argument _Term_
outputting the result to the string of character codes _Result_.
*/
write_to_chars(Term, Codes) :-
format(codes(Codes), '~w', [Term]).
/** @pred write_to_chars(+ _Term_, - _Result0_, - _Result_)
Execute the built-in procedure write/1 with argument _Term_
outputting the result to the difference list of character codes
_Result-Result0_.
*/
write_to_chars(Term, Out, Tail) :-
format(codes(Out,Tail),'~w',[Term]).
/** @pred atom_to_chars(+ _Atom_, - _Result_)
Convert the atom _Atom_ to the string of character codes
_Result_.
*/
atom_to_chars(Atom, OUT) :-
atom_codes(Atom, OUT).
/** @pred atom_to_chars(+ _Atom_, - _Result0_, - _Result_)
Convert the atom _Atom_ to the difference list of character codes
_Result-Result0_.
*/
atom_to_chars(Atom, L0, OUT) :-
format(codes(L0, OUT), '~a', [Atom]).
/** @pred number_to_chars(+ _Number_, - _Result_)
Convert the number _Number_ to the string of character codes
_Result_.
*/
number_to_chars(Number, OUT) :-
number_codes(Number, OUT).
/** @pred number_to_chars(+ _Number_, - _Result0_, - _Result_)
Convert the atom _Number_ to the difference list of character codes
_Result-Result0_.
*/
number_to_chars(Number, L0, OUT) :-
var(Number), !,
throw(error(instantiation_error,number_to_chars(Number, L0, OUT))).
@ -67,6 +116,10 @@ number_to_chars(Number, L0, OUT) :-
number_to_chars(Number, L0, OUT) :-
throw(error(type_error(number,Number),number_to_chars(Number, L0, OUT))).
/** @pred open_chars_stream(+ _Chars_, - _Stream_)
Open the list of character codes _Chars_ as a stream _Stream_.
*/
open_chars_stream(Codes, Stream) :-
open_chars_stream(Codes, Stream, '').
@ -83,9 +136,22 @@ open_chars_stream(Codes, Stream, Postfix) :-
ensure_loaded(library(memfile)),
open_chars_stream(Codes, Stream, Postfix).
/** @pred with_output_to_chars(? _Goal_, - _Chars_)
Execute goal _Goal_ such that its standard output will be sent to a
memory buffer. After successful execution the contents of the memory
buffer will be converted to the list of character codes _Chars_.
*/
with_output_to_chars(Goal, Codes) :-
with_output_to(codes(Codes), Goal).
/** @pred with_output_to_chars(? _Goal_, ? _Chars0_, - _Chars_)
Execute goal _Goal_ such that its standard output will be sent to a
memory buffer. After successful execution the contents of the memory
buffer will be converted to the difference list of character codes
_Chars-Chars0_.
*/
with_output_to_chars(Goal, Codes, L0) :-
with_output_to(codes(Codes, L0), Goal).
%% with_output_to_chars(:Goal, -Stream, -Codes, ?Tail) is det.
@ -93,6 +159,16 @@ with_output_to_chars(Goal, Codes, L0) :-
% As with_output_to_chars/2, but Stream is unified with the
% temporary stream.
/** @pred with_output_to_chars(? _Goal_, - _Stream_, ? _Chars0_, - _Chars_)
Execute goal _Goal_ such that its standard output will be sent to a
memory buffer. After successful execution the contents of the memory
buffer will be converted to the difference list of character codes
_Chars-Chars0_ and _Stream_ receives the stream corresponding to
the memory buffer.
*/
with_output_to_chars(Goal, Stream, Codes, Tail) :-
with_output_to(codes(Codes, Tail), with_stream(Stream, Goal)).
@ -100,14 +176,21 @@ with_stream(Stream, Goal) :-
current_output(Stream),
call(Goal).
%% read_from_chars(+Codes, -Term) is det.
%
% Read Codes into Term.
%
/** @pred read_from_chars(+ _Chars_, - _Term_)
Parse the list of character codes _Chars_ and return the result in
the term _Term_. The character codes to be read must terminate with
a dot character such that either (i) the dot character is followed by
blank characters; or (ii) the dot character is the last character in the
string.
% @compat The SWI-Prolog version does not require Codes to end
% in a full-stop.
*/
read_from_chars("", end_of_file) :- !.
read_from_chars(List, Term) :-
atom_to_term(List, Term, _).
/**
@}
*/

View File

@ -1,3 +1,23 @@
:- module( cleanup, [
call_cleanup/2,
call_cleanup/1,
on_cleanup/1,
cleanup_all/0,
op(1150, fx,fragile)
]).
%% @defgroup Cleanup Call Cleanup
% @ingroup YAPLibrary
% @{
%
% <tt>call_cleanup/1</tt> and <tt>call_cleanup/2</tt> allow predicates to register
% code for execution after the call is finished. Predicates can be
% declared to be <tt>fragile</tt> to ensure that <tt>call_cleanup</tt> is called
% for any Goal which needs it. This library is loaded with the
% `use_module(library(cleanup))` command.
%
% cleanup.yap
% Copyright (C) 2002 by Christian Thaeter
%
@ -28,13 +48,7 @@
% most private predicates could also be used in special cases, such as manually setting up cleanup-contexts.
% Read the Source.
:- module( cleanup, [
call_cleanup/2,
call_cleanup/1,
on_cleanup/1,
cleanup_all/0,
op(1150, fx,fragile)
]).
:- multifile user:goal_expansion/3.
@ -105,11 +119,31 @@ next_cleanup(CL) :-
next_cleanup(CL).
% clean up all remaining stuff / reinitialize cleanup-module
/** @pred cleanup_all
Calls all pending CleanUpGoals and resets the cleanup-system to an
initial state. Should only be used as one of the last calls in the
main program.
There are some private predicates which could be used in special
cases, such as manually setting up cleanup-contexts and registering
CleanUpGoals for other than the current cleanup-context.
Read the Source Luke.
*/
cleanup_all :-
do_cleanup(1).
cleanup_all.
% register a cleanup predicate (normal reverse-order cleanup)
/** @pred on_cleanup(+ _CleanUpGoal_)
Any Predicate might registers a _CleanUpGoal_. The
_CleanUpGoal_ is put onto the current cleanup context. All such
CleanUpGoals are executed in reverse order of their registration when
the surrounding cleanup-context ends. This call will throw an exception
if a predicate tries to register a _CleanUpGoal_ outside of any
cleanup-context.
*/
on_cleanup(G) :-
bb_get(cleanup_level,L),
on_cleanup(L,G).
@ -166,3 +200,7 @@ arity_to_vars(N,L1,L2) :-
LT = [L|L1],
arity_to_vars(NN,LT,L2).
arity_to_vars(0,L,L).
/**
@}
*/

View File

@ -119,6 +119,42 @@ outof_reducer([X|Xs]) :-
),
outof_reducer(Xs).
/** @pred all_distinct( _Cs_, _Vs_)
verifies whether all elements of a list are different. Also tests if
all the sums between a list of constants and a list of variables are
different.
This is a formulation of the queens problem that uses both versions of `all_different`:
~~~~~{.prolog}
queens(N, Queens) :-
length(Queens, N),
Queens ins 1..N,
all_distinct(Queens),
foldl(inc, Queens, Inc, 0, _), % [0, 1, 2, .... ]
foldl(dec, Queens, Dec, 0, _), % [0, -1, -2, ... ]
all_distinct(Inc,Queens),
all_distinct(Dec,Queens),
labeling([], Queens).
inc(_, I0, I0, I) :-
I is I0+1.
dec(_, I0, I0, I) :-
I is I0-1.
~~~~~
The next example uses `all_different/1` and the functionality of the matrix package to verify that all squares in
sudoku have a different value:
~~~~~{.prolog}
foreach( [I,J] ins 0..2 ,
all_different(M[I*3+(0..2),J*3+(0..2)]) ),
~~~~~
*/
all_distinct([], _).
all_distinct([X|Right], Left) :-
\+ list_contains(Right, X),
@ -255,6 +291,17 @@ num_subsets([S|Ss], Dom, Num0, Num) :-
is_subset(Dom, S) :-
S \/ Dom =:= Dom.
/** @pred attr_portray_hook(+ _AttValue_,+ _Var_)
Called by write_term/2 and friends for each attribute if the option
`attributes(portray)` is in effect. If the hook succeeds the
attribute is considered printed. Otherwise `Module = ...` is
printed to indicate the existence of a variable.
*/
attr_portray_hook(dom_neq(Dom,_,_), _) :-
Max is msb(Dom),
Min is lsb(Dom),

View File

@ -67,6 +67,138 @@
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
/** @pred _X_ #< _B_ is det
reified implication
As an example. consider finding out the people who wanted to sit
next to a friend and that are are actually sitting together:
~~~~~{.prolog}
preference_satisfied(X-Y, B) :-
abs(X - Y) #= 1 #<==> B.
~~~~~
Note that not all constraints may be reifiable.
*/
/** @pred _X_ #< _Y_ is semidet
smaller or equal
Arguments to this constraint may be an arithmetic expression with <tt>+</tt>,
<tt>-</tt>, <tt>\\*</tt>, integer division <tt>/</tt>, <tt>min</tt>, <tt>max</tt>, <tt>sum</tt>,
<tt>count</tt>, and
<tt>abs</tt>. Boolean variables support conjunction (/\), disjunction (\/),
implication (=>), equivalence (<=>), and xor. The <tt>sum</tt> constraint allows a two argument version using the
`where` conditional, in Zinc style.
The send more money equation may be written as:
~~~~~{.prolog}
1000*S + 100*E + 10*N + D +
1000*M + 100*O + 10*R + E #=
10000*M + 1000*O + 100*N + 10*E + Y,
~~~~~
This example uses `where` to select from
column _I_ the elements that have value under _M_:
~~~~~{.prolog}
OutFlow[I] #= sum(J in 1..N where D[J,I]<M, X[J,I])
~~~~~
The <tt>count</tt> constraint counts the number of elements that match a
certain constant or variable (integer sets are not available).
*/
/** @pred _X_ #<==> _B_ is det
reified equivalence
*/
/** @pred _X_ #= _Y_ is semidet
equality
*/
/** @pred _X_ #=< _Y_ is semidet
smaller
*/
/** @pred _X_ #==> _B_ is det
Reified implication
*/
/** @pred _X_ #> _Y_ is semidet
larger
*/
/** @pred _X_ #>= _Y_ is semidet
larger or equal
*/
/** @pred _X_ #\= _Y_ is semidet
disequality
*/
/** @pred all_different( _Vs_ )
Verifies whether all elements of a list are different.
*/
/** @pred labeling( _Opts_, _Xs_)
performs labeling, several variable and value selection options are
available. The defaults are `min` and `min_step`.
Variable selection options are as follows:
+ leftmost
choose the first variable
+ min
choose one of the variables with smallest minimum value
+ max
choose one of the variables with greatest maximum value
+ ff
choose one of the most constrained variables, that is, with the smallest
domain.
Given that we selected a variable, the values chosen for branching may
be:
+ min_step
smallest value
+ max_step
largest value
+ bisect
median
+ enum
all value starting from the minimum.
*/
/** @pred scalar_product(+ _Cs_, + _Vs_, + _Rel_, ? _V_ )
The product of constant _Cs_ by _Vs_ must be in relation
_Rel_ with _V_ .
*/
/** @pred transpose(+ _Graph_, - _NewGraph_)
Unify _NewGraph_ with a new graph obtained from _Graph_ by
replacing all edges of the form _V1-V2_ by edges of the form
_V2-V1_. The cost is `O(|V|^2)`. In the next example:
~~~~~{.prolog}
?- transpose([1-[3,5],2-[4],3-[],
4-[5],5-[],6-[],7-[],8-[]], NL).
NL = [1-[],2-[],3-[1],4-[2],5-[1,4],6-[],7-[],8-[]]
~~~~~
Notice that an undirected graph is its own transpose.
*/
:- module(clpfd, [
op(760, yfx, #<==>),
op(750, xfy, #==>),

View File

@ -8,10 +8,10 @@
* *
**************************************************************************
* *
* File: atts.yap *
* File: coinduction.yap *
* Last rev: 8/2/88 *
* mods: *
* comments: attribute support for Prolog *
* comments: coinduction support for Prolog *
* *
*************************************************************************/
@ -31,6 +31,7 @@
:- use_module(library(error)).
/** <module> Co-Logic Programming
@ingroup YAPLibrary
This simple module implements the directive coinductive/1 as described
in "Co-Logic Programming: Extending Logic Programming with Coinduction"
@ -38,7 +39,7 @@ by Luke Somin et al. The idea behind coinduction is that a goal succeeds
if it unifies to a parent goal. This enables some interesting programs,
notably on infinite trees (cyclic terms).
==
~~~~
:- use_module(library(coinduction)).
:- coinductive stream/1.
@ -52,7 +53,7 @@ notably on infinite trees (cyclic terms).
X= [s(s(A))|X], stream(X).
A = 0,
X = [s(s(0)),**]
==
~~~~
This predicate is true for any cyclic list containing only 1-s,
regardless of the cycle-length.
@ -162,6 +163,7 @@ writeG_val(G_var) :-
Some examples from Coinductive Logic Programming and its Applications by Gopal Gupta et al, ICLP 97
~~~~
:- coinductive stream/1.
stream([H|T]) :- i(H), stream(T).
@ -194,7 +196,8 @@ i(s(N)) :- i(N).
get_code(_),
fail.
~~~~
@}
**************************************/
*/

View File

@ -1,4 +1,15 @@
/** @defgroup DBUsage Memory Usage in Prolog Data-Base
@ingroup YAPLibrary
@{
This library provides a set of utilities for studying memory usage in YAP.
The following routines are available once included with the
`use_module(library(dbusage))` command.
*/
:- module(dbusage, [
db_usage/0,
db_static/0,
@ -7,6 +18,13 @@
db_dynamic/1
]).
/** @pred db_usage
Give general overview of data-base usage in the system.
*/
db_usage :-
statistics(heap,[HeapUsed,HeapFree]),
statistics(local_stack,[GInU,FreeS]),
@ -71,9 +89,23 @@ db_usage:-
write(mem_dump_error),nl.
/** @pred db_static
List memory usage for every static predicate.
*/
db_static :-
db_static(-1).
/** @pred db_static(+ _Threshold_)
List memory usage for every static predicate. Predicate must use more
than _Threshold_ bytes.
*/
db_static(Min) :-
setof(p(Sz,M:P,Cls,CSz,ISz),
PN^(current_module(M),
@ -85,9 +117,25 @@ db_static(Min) :-
format(user_error,' Static user code~n===========================~n',[]),
display_preds(All).
/** @pred db_dynamic
List memory usage for every dynamic predicate.
*/
db_dynamic :-
db_dynamic(-1).
/** @pred db_dynamic(+ _Threshold_)
List memory usage for every dynamic predicate. Predicate must use more
than _Threshold_ bytes.
*/
db_dynamic(Min) :-
setof(p(Sz,M:P,Cls,CSz,ISz,ECls,ECSz,EISz),
PN^(current_module(M),

View File

@ -3,6 +3,278 @@
% Updated: 2006
% Purpose: Directed Graph Processing Utilities.
/** @defgroup DGraphs Directed Graphs
@ingroup YAPLibrary
@{
The following graph manipulation routines use the red-black tree library
to try to avoid linear-time scans of the graph for all graph
operations. Graphs are represented as a red-black tree, where the key is
the vertex, and the associated value is a list of vertices reachable
from that vertex through an edge (ie, a list of edges).
@pred dgraph_new(+ _Graph_)
Create a new directed graph. This operation must be performed before
trying to use the graph.
*/
/** @pred dgraph_add_edge(+ _Graph_, + _N1_, + _N2_, - _NewGraph_)
Unify _NewGraph_ with a new graph obtained by adding the edge
_N1_- _N2_ to the graph _Graph_.
*/
/** @pred dgraph_add_edges(+ _Graph_, + _Edges_, - _NewGraph_)
Unify _NewGraph_ with a new graph obtained by adding the list of
edges _Edges_ to the graph _Graph_.
*/
/** @pred dgraph_add_vertices(+ _Graph_, + _Vertex_, - _NewGraph_)
Unify _NewGraph_ with a new graph obtained by adding
vertex _Vertex_ to the graph _Graph_.
*/
/** @pred dgraph_add_vertices(+ _Graph_, + _Vertices_, - _NewGraph_)
Unify _NewGraph_ with a new graph obtained by adding the list of
vertices _Vertices_ to the graph _Graph_.
*/
/** @pred dgraph_complement(+ _Graph_, - _NewGraph_)
Unify _NewGraph_ with the graph complementary to _Graph_.
*/
/** @pred dgraph_compose(+ _Graph1_, + _Graph2_, - _ComposedGraph_)
Unify _ComposedGraph_ with a new graph obtained by composing
_Graph1_ and _Graph2_, ie, _ComposedGraph_ has an edge
_V1-V2_ iff there is a _V_ such that _V1-V_ in _Graph1_
and _V-V2_ in _Graph2_.
*/
/** @pred dgraph_del_edge(+ _Graph_, + _N1_, + _N2_, - _NewGraph_)
Succeeds if _NewGraph_ unifies with a new graph obtained by
removing the edge _N1_- _N2_ from the graph _Graph_. Notice
that no vertices are deleted.
*/
/** @pred dgraph_del_edges(+ _Graph_, + _Edges_, - _NewGraph_)
Unify _NewGraph_ with a new graph obtained by removing the list of
edges _Edges_ from the graph _Graph_. Notice that no vertices
are deleted.
*/
/** @pred dgraph_del_vertex(+ _Graph_, + _Vertex_, - _NewGraph_)
Unify _NewGraph_ with a new graph obtained by deleting vertex
_Vertex_ and all the edges that start from or go to _Vertex_ to
the graph _Graph_.
*/
/** @pred dgraph_del_vertices(+ _Graph_, + _Vertices_, - _NewGraph_)
Unify _NewGraph_ with a new graph obtained by deleting the list of
vertices _Vertices_ and all the edges that start from or go to a
vertex in _Vertices_ to the graph _Graph_.
*/
/** @pred dgraph_edge(+ _N1_, + _N2_, + _Graph_)
Edge _N1_- _N2_ is an edge in directed graph _Graph_.
*/
/** @pred dgraph_edges(+ _Graph_, - _Edges_)
Unify _Edges_ with all edges appearing in graph
_Graph_.
*/
/** @pred dgraph_isomorphic(+ _Vs_, + _NewVs_, + _G0_, - _GF_)
Unify the list _GF_ with the graph isomorphic to _G0_ where
vertices in _Vs_ map to vertices in _NewVs_.
*/
/** @pred dgraph_leaves(+ _Graph_, ? _Vertices_)
The vertices _Vertices_ have no outgoing edge in graph
_Graph_.
*/
/** @pred dgraph_max_path(+ _V1_, + _V1_, + _Graph_, - _Path_, ? _Costt_)
Unify the list _Path_ with the maximal cost path between nodes
_N1_ and _N2_ in graph _Graph_. Path _Path_ has cost
_Cost_.
*/
/** @pred dgraph_min_path(+ _V1_, + _V1_, + _Graph_, - _Path_, ? _Costt_)
Unify the list _Path_ with the minimal cost path between nodes
_N1_ and _N2_ in graph _Graph_. Path _Path_ has cost
_Cost_.
*/
/** @pred dgraph_min_paths(+ _V1_, + _Graph_, - _Paths_)
Unify the list _Paths_ with the minimal cost paths from node
_N1_ to the nodes in graph _Graph_.
*/
/** @pred dgraph_neighbors(+ _Vertex_, + _Graph_, - _Vertices_)
Unify _Vertices_ with the list of neighbors of vertex _Vertex_
in _Graph_. If the vertice is not in the graph fail.
*/
/** @pred dgraph_neighbours(+ _Vertex_, + _Graph_, - _Vertices_)
Unify _Vertices_ with the list of neighbours of vertex _Vertex_
in _Graph_.
*/
/** @pred dgraph_path(+ _Vertex_, + _Graph_, ? _Path_)
The path _Path_ is a path starting at vertex _Vertex_ in graph
_Graph_.
*/
/** @pred dgraph_path(+ _Vertex_, + _Vertex1_, + _Graph_, ? _Path_)
The path _Path_ is a path starting at vertex _Vertex_ in graph
_Graph_ and ending at path _Vertex2_.
*/
/** @pred dgraph_reachable(+ _Vertex_, + _Graph_, ? _Edges_)
The path _Path_ is a path starting at vertex _Vertex_ in graph
_Graph_.
*/
/** @pred dgraph_symmetric_closure(+ _Graph_, - _Closure_)
Unify _Closure_ with the symmetric closure of graph _Graph_,
that is, if _Closure_ contains an edge _U-V_ it must also
contain the edge _V-U_.
*/
/** @pred dgraph_to_ugraph(+ _Graph_, - _UGraph_)
Unify _UGraph_ with the representation used by the _ugraphs_
unweighted graphs library, that is, a list of the form
_V-Neighbors_, where _V_ is a node and _Neighbors_ the nodes
children.
*/
/** @pred dgraph_top_sort(+ _Graph_, - _Vertices_)
Unify _Vertices_ with the topological sort of graph _Graph_.
*/
/** @pred dgraph_top_sort(+ _Graph_, - _Vertices_, ? _Vertices0_)
Unify the difference list _Vertices_- _Vertices0_ with the
topological sort of graph _Graph_.
*/
/** @pred dgraph_transitive_closure(+ _Graph_, - _Closure_)
Unify _Closure_ with the transitive closure of graph _Graph_.
*/
/** @pred dgraph_transpose(+ _Graph_, - _Transpose_)
Unify _NewGraph_ with a new graph obtained from _Graph_ by
replacing all edges of the form _V1-V2_ by edges of the form
_V2-V1_.
*/
/** @pred dgraph_vertices(+ _Graph_, - _Vertices_)
Unify _Vertices_ with all vertices appearing in graph
_Graph_.
*/
/** @pred ugraph_to_dgraph( + _UGraph_, - _Graph_)
Unify _Graph_ with the directed graph obtain from _UGraph_,
represented in the form used in the _ugraphs_ unweighted graphs
library.
*/
:- module( dgraphs,
[
dgraph_vertices/2,

View File

@ -137,6 +137,12 @@ foreach(A1,A2,A3,A4,A5,A6):-
foreach(A1,A2,A3,A4,A5):-
foreach_aux((A1,A2),A3,A4,A5).
/** @pred foreach( _Sequence_, _Goal_, _Acc0_, _AccF_)
Deterministic iterator with accumulator style arguments.
*/
foreach(A1,A2,A3,A4):-
foreach_aux(A1,A2,A3,A4).
@ -165,6 +171,55 @@ foreach_aux(A1,A2,A3):-
foreach_check_lvars(A2),!,
interp_foreach(A1,true,A2,A3,[],[],_).
/** @pred foreach( _Sequence_, _Goal_)
Deterministic iterator. The ranges are given by _Sequence_ that is
either ` _I_ in _M_.. _N_`, or of the form
`[ _I_, _J_] ins _M_.. _N_`, or a list of the above conditions.
Variables in the goal are assumed to be global, ie, share a single value
in the execution. The exceptions are the iteration indices. Moreover, if
the goal is of the form ` _Locals_^ _G_` all variables
occurring in _Locals_ are marked as local. As an example:
~~~~~{.prolog}
foreach([I,J] ins 1..N, A^(A <==M[I,J], N[I] <== N[I] + A*A) )
~~~~~
the variables _I_, _J_ and _A_ are duplicated for every
call (local), whereas the matrices _M_ and _N_ are shared
throughout the execution (global).
*/
/** @pred foreach(:Generator, : _Goal_)
True if the conjunction of instances of _Goal_ using the
bindings from Generator is true. Unlike forall/2, which runs a
failure-driven loop that proves _Goal_ for each solution of
Generator, foreach creates a conjunction. Each member of the
conjunction is a copy of _Goal_, where the variables it shares
with Generator are filled with the values from the corresponding
solution.
The implementation executes forall/2 if _Goal_ does not contain
any variables that are not shared with Generator.
Here is an example:
~~~~~{.prolog}
?- foreach( between(1,4,X), dif(X,Y)), Y = 5.
Y = 5
?- foreach( between(1,4,X), dif(X,Y)), Y = 3.
No
~~~~~
Notice that _Goal_ is copied repeatedly, which may cause
problems if attributed variables are involved.
*/
foreach(Iterators,Goal):-
interp_foreach(Iterators,true,[],Goal,[],[],_).

View File

@ -3,6 +3,72 @@
% written in an on-demand basis.
/**
@defgroup system
@file swi.yap
@page SWIhYProlog_Emulation SWI-Prolog Emulation
This library provides a number of SWI-Prolog builtins that are not by
default in YAP. This support is loaded with the
`expects_dialect(swi)` command.
*/
/** @pred time_file(+ _File_,- _Time_)
Unify the last modification time of _File_ with
_Time_. _Time_ is a floating point number expressing the seconds
elapsed since Jan 1, 1970.
*/
/** @pred chdir(+ _Dir_)
Compatibility predicate. New code should use working_directory/2.
*/
/** @pred concat_atom(+ _List_,- _Atom_)
_List_ is a list of atoms, integers or floating point numbers. Succeeds
if _Atom_ can be unified with the concatenated elements of _List_. If
_List_ has exactly 2 elements it is equivalent to `atom_concat/3`,
allowing for variables in the list.
*/
/** @pred concat_atom(? _List_,+ _Separator_,? _Atom_)
Creates an atom just like concat_atom/2, but inserts _Separator_
between each pair of atoms. For example:
~~~~~
?- concat_atom([gnu, gnat], ', ', A).
A = 'gnu, gnat'
~~~~~
(Unimplemented) This predicate can also be used to split atoms by
instantiating _Separator_ and _Atom_:
~~~~~
?- concat_atom(L, -, 'gnu-gnat').
L = [gnu, gnat]
~~~~~
*/
:- module(system, [concat_atom/2,
concat_atom/3,
read_clause/1,
@ -98,8 +164,32 @@
swi_get_time(FSecs) :- datime(Datime), mktime(Datime, Secs), FSecs is Secs*1.0.
goal_expansion(atom_concat(A,B),atomic_concat(A,B)).
/** @pred atom_concat(? _A1_,? _A2_,? _A12_) is iso
The predicate holds when the third argument unifies with an atom, and
the first and second unify with atoms such that their representations
concatenated are the representation for _A12_.
If _A1_ and _A2_ are unbound, the built-in will find all the atoms
that concatenated give _A12_.
*/
goal_expansion(atom_concat(A,B,C),atomic_concat(A,B,C)).
%goal_expansion(arg(A,_,_),_) :- nonvar(A), !, fail.
/** @pred arg(+ _N_,+ _T_, _A_) is iso
Succeeds if the argument _N_ of the term _T_ unifies with
_A_. The arguments are numbered from 1 to the arity of the term.
The current version will generate an error if _T_ or _N_ are
unbound, if _T_ is not a compound term, of if _N_ is not a positive
integer. Note that previous versions of YAP would fail silently
under these errors.
@}
*/
goal_expansion(arg(A,B,C),genarg(A,B,C)).
% make sure we also use

View File

@ -12,6 +12,7 @@
@file swi.h
@defgroup swi-c-interface SWI-Prolog Foreign Language Interface
@ingroup ChYInterface
*
* @tableofcontents

View File

@ -6,6 +6,73 @@
% and does not really expect to do non-trivial
% constraint propagation and solving.
/** @defgroup Exo_Intervals Exo Intervals
@ingroup YAPLibrary
@{
This package assumes you use exo-compilation, that is, that you loaded
the pedicate using the `exo` option to load_files/2, In this
case, YAP includes a package for improved search on intervals of
integers.
The package is activated by `udi` declarations that state what is
the argument of interest:
~~~~~{.prolog}
:- udi(diagnoses(exo_interval,?,?)).
:- load_files(db, [consult(exo)]).
~~~~~
It is designed to optimise the following type of queries:
~~~~~{.prolog}
?- max(X, diagnoses(X, 9, Y), X).
?- min(X, diagnoses(X, 9, 36211117), X).
?- X #< Y, min(X, diagnoses(X, 9, 36211117), X ), diagnoses(Y, 9, _).
~~~~~
The first argument gives the time, the second the patient, and the
third the condition code. The first query should find the last time
the patient 9 had any code reported, the second looks for the first
report of code 36211117, and the last searches for reports after this
one. All queries run in constant or log(n) time.
*/
/** @pred max( _X_, _Vs_)
First Argument is the greatest element of a list.
+ lex_order( _Vs_)
All elements must be ordered.
The following predicates control search:
*/
/** @pred max(+ _Expression_)
Maximizes _Expression_ within the current constraint store. This is
the same as computing the supremum and equating the expression to that
supremum.
*/
/** @pred min( _X_, _Vs_)
First Argument is the least element of a list.
*/
/** @pred min(+ _Expression_)
Minimizes _Expression_ within the current constraint store. This is
the same as computing the infimum and equation the expression to that
infimum.
*/
:- module(exo_interval,
[max/2,
min/2,

View File

@ -5,6 +5,27 @@
% Updated: 29 November 1983
% Purpose: Implement heaps in Prolog.
/** @defgroup Heaps Heaps
@ingroup YAPLibrary
@{
A heap is a labelled binary tree where the key of each node is less than
or equal to the keys of its sons. The point of a heap is that we can
keep on adding new elements to the heap and we can keep on taking out
the minimum element. If there are N elements total, the total time is
O(NlgN). If you know all the elements in advance, you are better off
doing a merge-sort, but this file is for when you want to do say a
best-first search, and have no idea when you start how many elements
there will be, let alone what they are.
The following heap manipulation routines are available once included
with the `use_module(library(heaps))` command.
*/
/* A heap is a labelled binary tree where the key of each node is less
than or equal to the keys of its sons. The point of a heap is that
we can keep on adding new elements to the heap and we can keep on
@ -40,6 +61,74 @@
*/
/**
@pred add_to_heap(+ _Heap_,+ _key_,+ _Datum_,- _NewHeap_)
Inserts the new _Key-Datum_ pair into the heap. The insertion is not
stable, that is, if you insert several pairs with the same _Key_ it
is not defined which of them will come out first, and it is possible for
any of them to come out first depending on the history of the heap.
*/
/** @pred empty_heap(? _Heap_)
Succeeds if _Heap_ is an empty heap.
*/
/** @pred get_from_heap(+ _Heap_,- _key_,- _Datum_,- _Heap_)
Returns the _Key-Datum_ pair in _OldHeap_ with the smallest
_Key_, and also a _Heap_ which is the _OldHeap_ with that
pair deleted.
*/
/** @pred heap_size(+ _Heap_, - _Size_)
Reports the number of elements currently in the heap.
*/
/** @pred heap_to_list(+ _Heap_, - _List_)
Returns the current set of _Key-Datum_ pairs in the _Heap_ as a
_List_, sorted into ascending order of _Keys_.
*/
/** @pred list_to_heap(+ _List_, - _Heap_)
Takes a list of _Key-Datum_ pairs (such as keysort could be used to sort)
and forms them into a heap.
*/
/** @pred min_of_heap(+ _Heap_, - _Key1_, - _Datum1_,
- _Key2_, - _Datum2_)
Returns the smallest (Key1) and second smallest (Key2) pairs in the
heap, without deleting them.
*/
/** @pred min_of_heap(+ _Heap_, - _Key_, - _Datum_)
Returns the Key-Datum pair at the top of the heap (which is of course
the pair with the smallest Key), but does not remove it from the heap.
*/
:- module(heaps,[
add_to_heap/4, % Heap x Key x Datum -> Heap
get_from_heap/4, % Heap -> Key x Datum x Heap

View File

@ -2,6 +2,190 @@
% Date: 2006-06-01
% $Id: lam_mpi.yap,v 1.1 2006-06-04 18:43:38 nunofonseca Exp $
/** @defgroup LAM LAM
@ingroup YAPLibrary
@{
This library provides a set of utilities for interfacing with LAM MPI.
The following routines are available once included with the
`use_module(library(lam_mpi))` command. The yap should be
invoked using the LAM mpiexec or mpirun commands (see LAM manual for
more details).
*/
/** @pred mpi_barrier
Collective communication predicate. Performs a barrier
synchronization among all processes. Note that a collective
communication means that all processes call the same predicate. To be
able to use a regular `mpi_recv` to receive the messages, one
should use `mpi_bcast2`.
*/
/** @pred mpi_bcast2(+ _Root_, ? _Data_)
Broadcasts the message _Data_ from the process with rank _Root_
to all other processes.
*/
/** @pred mpi_comm_rank(- _Rank_)
Unifies _Rank_ with the rank of the current process in the MPI environment.
*/
/** @pred mpi_comm_size(- _Size_)
Unifies _Size_ with the number of processes in the MPI environment.
*/
/** @pred mpi_finalize
Terminates the MPI execution environment. Every process must call this predicate before exiting.
*/
/** @pred mpi_gc
Attempts to perform garbage collection with all the open handles
associated with send and non-blocking broadcasts. For each handle it
tests it and the message has been delivered the handle and the buffer
are released.
*/
/** @pred mpi_init
Sets up the mpi environment. This predicate should be called before any other MPI predicate.
*/
/** @pred mpi_irecv(? _Source_,? _Tag_,- _Handle_)
Non-blocking communication predicate. The predicate returns an
_Handle_ for a message that will be received from processor with
rank _Source_ and tag _Tag_. Note that the predicate succeeds
immediately, even if no message has been received. The predicate
`mpi_wait_recv` should be used to obtain the data associated to
the handle.
*/
/** @pred mpi_isend(+ _Data_,+ _Dest_,+ _Tag_,- _Handle_)
Non blocking communication predicate. The message in _Data_, with
tag _Tag_, is sent whenever possible to the processor with rank
_Dest_. An _Handle_ to the message is returned to be used to
check for the status of the message, using the `mpi_wait` or
`mpi_test` predicates. Until `mpi_wait` is called, the
memory allocated for the buffer containing the message is not
released.
*/
/** @pred mpi_msg_size( _Msg_, - _MsgSize_)
Unify _MsgSize_ with the number of bytes YAP would need to send the
message _Msg_.
*/
/** @pred mpi_recv(? _Source_,? _Tag_,- _Data_)
Blocking communication predicate. The predicate blocks until a message
is received from processor with rank _Source_ and tag _Tag_.
The message is placed in _Data_.
*/
/** @pred mpi_send(+ _Data_,+ _Dest_,+ _Tag_)
Blocking communication predicate. The message in _Data_, with tag
_Tag_, is sent immediately to the processor with rank _Dest_.
The predicate succeeds after the message being sent.
*/
/** @pred mpi_test(? _Handle_,- _Status_)
Provides information regarding the handle _Handle_, ie., if a
communication operation has been completed. If the operation
associate with _Hanlde_ has been completed the predicate succeeds
with the completion status in _Status_, otherwise it fails.
*/
/** @pred mpi_test_recv(? _Handle_,- _Status_,- _Data_)
Provides information regarding a handle. If the message associated
with handle _Hanlde_ is buffered then the predicate succeeds
unifying _Status_ with the status of the message and _Data_
with the message itself. Otherwise, the predicate fails.
*/
/** @pred mpi_version(- _Major_,- _Minor_)
Unifies _Major_ and _Minor_ with, respectively, the major and minor version of the MPI.
*/
/** @pred mpi_wait(? _Handle_,- _Status_)
Completes a non-blocking operation. If the operation was a
`mpi_send`, the predicate blocks until the message is buffered
or sent by the runtime system. At this point the send buffer is
released. If the operation was a `mpi_recv`, it waits until the
message is copied to the receive buffer. _Status_ is unified with
the status of the message.
*/
/** @pred mpi_wait_recv(? _Handle_,- _Status_,- _Data_)
Completes a non-blocking receive operation. The predicate blocks until
a message associated with handle _Hanlde_ is buffered. The
predicate succeeds unifying _Status_ with the status of the
message and _Data_ with the message itself.
*/
:- module(lam_mpi, [
mpi_init/0,
mpi_finalize/0,
@ -31,4 +215,4 @@
mpi_msg_size(Term, Size) :-
terms:export_term(Term, Buf, Size),
terms:kill_exported_term(Buf).
terms:kill_exported_term(Buf).

View File

@ -41,6 +41,7 @@ official policies, either expressed or implied, of Ulrich Neumerkel.
op(201,xfx,+\)]).
/** <module> Lambda expressions
@ingroup YAPLibrary
This library provides lambda expressions to simplify higher order
programming based on call/N.

View File

@ -1026,11 +1026,40 @@ init_mpi(void) {
YAP_UserCPredicate( "mpi_bcast", mpi_bcast,2); // mpi_bcast(Root,Term)
YAP_UserCPredicate( "mpi_bcast2", mpi_bcast2,2); // mpi_bcast2(Root,Term)
YAP_UserCPredicate( "mpi_bcast3", mpi_bcast3,3); // mpi_bcast3(Root,Term,Tag)
/** @pred mpi_bcast3(+ _Root_, + _Data_, + _Tag_)
Broadcasts the message _Data_ with tag _Tag_ from the process with rank _Root_
to all other processes.
*/
YAP_UserCPredicate( "mpi_ibcast", mpi_ibcast2,2); // mpi_ibcast(Root,Term)
YAP_UserCPredicate( "mpi_ibcast", mpi_ibcast3,3); // mpi_ibcast(Root,Term,Tag)
/** @pred mpi_ibcast(+ _Root_, + _Data_, + _Tag_)
Non-blocking operation. Broadcasts the message _Data_ with tag _Tag_
from the process with rank _Root_ to all other processes.
*/
YAP_UserCPredicate( "mpi_barrier", mpi_barrier,0); // mpi_barrier/0
YAP_UserCPredicate( "mpi_gc", mpi_gc,0); // mpi_gc/0
YAP_UserCPredicate( "mpi_default_buffer_size", mpi_default_buffer_size,2); // buffer size
/** @pred mpi_default_buffer_size(- _OldBufferSize_, ? _NewBufferSize_)
The _OldBufferSize_ argument unifies with the current size of the
MPI communication buffer size and sets the communication buffer size
_NewBufferSize_. The buffer is used for assynchronous waiting and
for broadcast receivers. Notice that buffer is local at each MPI
process.
*/
#ifdef MPISTATS
YAP_UserCPredicate( "mpi_stats", mpi_stats,7); // mpi_stats(-Time,#MsgsRecv,BytesRecv,MaxRecev,#MsgSent,BytesSent,MaxSent)
YAP_UserCPredicate( "mpi_reset_stats", mpi_reset_stats,0); // cleans the timers

View File

@ -1,3 +1,23 @@
/** @defgroup LineUtilities Line Manipulation Utilities
@ingroup YAPLibrary
@{
This package provides a set of useful predicates to manipulate
sequences of characters codes, usually first read in as a line. It is
available by loading the library `library(lineutils)`.
@pred search_for(+ _Char_,+ _Line_)
Search for a character _Char_ in the list of codes _Line_.
*/
:- module(line_utils,
[search_for/2,
search_for/3,

View File

@ -3,6 +3,262 @@
%
% This file includes code from Bob Welham, Lawrence Byrd, and R. A. O'Keefe.
%
/** @defgroup Lists List Manipulation
@ingroup YAPLibrary
@{
The following list manipulation routines are available once included
with the `use_module(library(lists))` command.
*/
/**
@pred append(? _Prefix_,? _Suffix_,? _Combined_)
True when all three arguments are lists, and the members of
_Combined_ are the members of _Prefix_ followed by the members of _Suffix_.
It may be used to form _Combined_ from a given _Prefix_, _Suffix_ or to take
a given _Combined_ apart.
*/
/** @pred append(? _Lists_,? _Combined_)
Holds if the lists of _Lists_ can be concatenated as a
_Combined_ list.
*/
/** @pred flatten(+ _List_, ? _FlattenedList_)
Flatten a list of lists _List_ into a single list
_FlattenedList_.
~~~~~{.prolog}
?- flatten([[1],[2,3],[4,[5,6],7,8]],L).
L = [1,2,3,4,5,6,7,8] ? ;
no
~~~~~
*/
/** @pred intersection(+ _Set1_, + _Set2_, + _Set3_)
Succeeds if _Set3_ unifies with the intersection of _Set1_ and
_Set2_. _Set1_ and _Set2_ are lists without duplicates. They
need not be ordered.
*/
/** @pred last(+ _List_,? _Last_)
True when _List_ is a list and _Last_ is identical to its last element.
*/
/** @pred list_concat(+ _Lists_,? _List_)
True when _Lists_ is a list of lists and _List_ is the
concatenation of _Lists_.
*/
/** @pred max_list(? _Numbers_, ? _Max_)
True when _Numbers_ is a list of numbers, and _Max_ is the maximum.
*/
/** @pred min_list(? _Numbers_, ? _Min_)
True when _Numbers_ is a list of numbers, and _Min_ is the minimum.
*/
/** @pred nth(? _N_, ? _List_, ? _Elem_)
The same as nth1/3.
*/
/** @pred nth(? _N_, ? _List_, ? _Elem_, ? _Rest_)
Same as `nth1/4`.
*/
/** @pred nth0(? _N_, ? _List_, ? _Elem_)
True when _Elem_ is the Nth member of _List_,
counting the first as element 0. (That is, throw away the first
N elements and unify _Elem_ with the next.) It can only be used to
select a particular element given the list and index. For that
task it is more efficient than member/2
*/
/** @pred nth0(? _N_, ? _List_, ? _Elem_, ? _Rest_)
Unifies _Elem_ with the Nth element of _List_,
counting from 0, and _Rest_ with the other elements. It can be used
to select the Nth element of _List_ (yielding _Elem_ and _Rest_), or to
insert _Elem_ before the Nth (counting from 1) element of _Rest_, when
it yields _List_, e.g. `nth0(2, List, c, [a,b,d,e])` unifies List with
`[a,b,c,d,e]`. `nth/4` is the same except that it counts from 1. `nth0/4`
can be used to insert _Elem_ after the Nth element of _Rest_.
*/
/** @pred nth1(+ _Index_,? _List_,? _Elem_)
Succeeds when the _Index_-th element of _List_ unifies with
_Elem_. Counting starts at 1.
Set environment variable. _Name_ and _Value_ should be
instantiated to atoms or integers. The environment variable will be
passed to `shell/[0-2]` and can be requested using `getenv/2`.
They also influence expand_file_name/2.
*/
/** @pred nth1(? _N_, ? _List_, ? _Elem_)
The same as nth0/3, except that it counts from
1, that is `nth(1, [H|_], H)`.
*/
/** @pred nth1(? _N_, ? _List_, ? _Elem_, ? _Rest_)
Unifies _Elem_ with the Nth element of _List_, counting from 1,
and _Rest_ with the other elements. It can be used to select the
Nth element of _List_ (yielding _Elem_ and _Rest_), or to
insert _Elem_ before the Nth (counting from 1) element of
_Rest_, when it yields _List_, e.g. `nth(3, List, c, [a,b,d,e])` unifies List with `[a,b,c,d,e]`. `nth/4`
can be used to insert _Elem_ after the Nth element of _Rest_.
*/
/** @pred numlist(+ _Low_, + _High_, + _List_)
If _Low_ and _High_ are integers with _Low_ =<
_High_, unify _List_ to a list `[Low, Low+1, ...High]`. See
also between/3.
*/
/** @pred permutation(+ _List_,? _Perm_)
True when _List_ and _Perm_ are permutations of each other.
*/
/** @pred remove_duplicates(+ _List_, ? _Pruned_)
Removes duplicated elements from _List_. Beware: if the _List_ has
non-ground elements, the result may surprise you.
*/
/** @pred same_length(? _List1_, ? _List2_)
True when _List1_ and _List2_ are both lists and have the same number
of elements. No relation between the values of their elements is
implied.
Modes `same_length(-,+)` and `same_length(+,-)` generate either list given
the other; mode `same_length(-,-)` generates two lists of the same length,
in which case the arguments will be bound to lists of length 0, 1, 2, ...
*/
/** @pred select(? _Element_, ? _List_, ? _Residue_)
True when _Set_ is a list, _Element_ occurs in _List_, and
_Residue_ is everything in _List_ except _Element_ (things
stay in the same order).
*/
/** @pred selectchk(? _Element_, ? _List_, ? _Residue_)
Semi-deterministic selection from a list. Steadfast: defines as
~~~~~{.prolog}
selectchk(Elem, List, Residue) :-
select(Elem, List, Rest0), !,
Rest = Rest0.
~~~~~
*/
/** @pred sublist(? _Sublist_, ? _List_)
True when both `append(_,Sublist,S)` and `append(S,_,List)` hold.
*/
/** @pred subtract(+ _Set_, + _Delete_, ? _Result_)
Delete all elements from _Set_ that occur in _Delete_ (a set)
and unify the result with _Result_. Deletion is based on
unification using memberchk/2. The complexity is
`|Delete|\*|Set|`.
See ord_subtract/3.
*/
/** @pred suffix(? _Suffix_, ? _List_)
Holds when `append(_,Suffix,List)` holds.
*/
/** @pred sum_list(? _Numbers_, + _SoFar_, ? _Total_)
True when _Numbers_ is a list of numbers, and _Total_ is the sum of their total plus _SoFar_.
*/
/** @pred sum_list(? _Numbers_, ? _Total_)
True when _Numbers_ is a list of numbers, and _Total_ is their sum.
*/
/** @pred sumlist(? _Numbers_, ? _Total_)
True when _Numbers_ is a list of integers, and _Total_ is their
sum. The same as sum_list/2, please do use sum_list/2
instead.
*/
:- module(lists,
[
append/3,

View File

@ -15,6 +15,7 @@
* @file maplist.yap
*
* @defgroup maplist Map List and Term Operations
* @ingroup YAPLibrary
*
* This library provides a set of utilities for applying a predicate to
* all elements of a list. They allow one to easily perform the most common do-loop constructs in Prolog.
@ -71,6 +72,25 @@ trans(X,X).
*/
/** @pred maplist(+ _Pred_,+ _List1_,+ _List2_)
Apply _Pred_ on all successive pairs of elements from
_List1_ and
_List2_. Fails if _Pred_ can not be applied to a
pair. See the example above.
*/
/** @pred maplist(+ _Pred_,+ _List1_,+ _List2_,+ _List4_)
Apply _Pred_ on all successive triples of elements from _List1_,
_List2_ and _List3_. Fails if _Pred_ can not be applied to a
triple. See the example above.
*/
:- module(maplist, [selectlist/3,
selectlist/4,
selectlists/5,

View File

@ -1,4 +1,195 @@
/** @defgroup MATLAB MATLAB Package Interface
@ingroup YAPLibrary
@{
The MathWorks MATLAB is a widely used package for array
processing. YAP now includes a straightforward interface to MATLAB. To
actually use it, you need to install YAP calling `configure` with
the `--with-matlab=DIR` option, and you need to call
`use_module(library(lists))` command.
Accessing the matlab dynamic libraries can be complicated. In Linux
machines, to use this interface, you may have to set the environment
variable <tt>LD_LIBRARY_PATH</tt>. Next, follows an example using bash in a
64-bit Linux PC:
~~~~~
export LD_LIBRARY_PATH=''$MATLAB_HOME"/sys/os/glnxa64:''$MATLAB_HOME"/bin/glnxa64:''$LD_LIBRARY_PATH"
~~~~~
where `MATLAB_HOME` is the directory where matlab is installed
at. Please replace `ax64` for `x86` on a 32-bit PC.
@pred start_matlab(+ _Options_)
Start a matlab session. The argument _Options_ may either be the
empty string/atom or the command to call matlab. The command may fail.
*/
/** @pred close_matlab
Stop the current matlab session.
*/
/** @pred matlab_cells(+ _SizeX_, + _SizeY_, ? _Array_)
MATLAB will create an empty array of cells of size _SizeX_ and
_SizeY_, and if _Array_ is bound to an atom, store the array
in the matlab variable with name _Array_. Corresponds to the
MATLAB command `cells`.
*/
/** @pred matlab_cells(+ _Size_, ? _Array_)
MATLAB will create an empty vector of cells of size _Size_, and if
_Array_ is bound to an atom, store the array in the matlab
variable with name _Array_. Corresponds to the MATLAB command `cells`.
*/
/** @pred matlab_eval_string(+ _Command_)
Holds if matlab evaluated successfully the command _Command_.
*/
/** @pred matlab_eval_string(+ _Command_, - _Answer_)
MATLAB will evaluate the command _Command_ and unify _Answer_
with a string reporting the result.
*/
/** @pred matlab_get_variable(+ _MatVar_, - _List_)
Unify MATLAB variable _MatVar_ with the List _List_.
*/
/** @pred matlab_initialized_cells(+ _SizeX_, + _SizeY_, + _List_, ? _Array_)
MATLAB will create an array of cells of size _SizeX_ and
_SizeY_, initialized from the list _List_, and if _Array_
is bound to an atom, store the array in the matlab variable with name
_Array_.
*/
/** @pred matlab_item(+ _MatVar_, + _X_, + _Y_, ? _Val_)
Read or set MATLAB _MatVar_( _X_, _Y_) from/to _Val_. Use
`C` notation for matrix access (ie, starting from 0).
*/
/** @pred matlab_item(+ _MatVar_, + _X_, ? _Val_)
Read or set MATLAB _MatVar_( _X_) from/to _Val_. Use
`C` notation for matrix access (ie, starting from 0).
*/
/** @pred matlab_item1(+ _MatVar_, + _X_, + _Y_, ? _Val_)
Read or set MATLAB _MatVar_( _X_, _Y_) from/to _Val_. Use
MATLAB notation for matrix access (ie, starting from 1).
*/
/** @pred matlab_item1(+ _MatVar_, + _X_, ? _Val_)
Read or set MATLAB _MatVar_( _X_) from/to _Val_. Use
MATLAB notation for matrix access (ie, starting from 1).
*/
/** @pred matlab_matrix(+ _SizeX_, + _SizeY_, + _List_, ? _Array_)
MATLAB will create an array of floats of size _SizeX_ and _SizeY_,
initialized from the list _List_, and if _Array_ is bound to
an atom, store the array in the matlab variable with name _Array_.
*/
/** @pred matlab_on
Holds if a matlab session is on.
*/
/** @pred matlab_sequence(+ _Min_, + _Max_, ? _Array_)
MATLAB will create a sequence going from _Min_ to _Max_, and
if _Array_ is bound to an atom, store the sequence in the matlab
variable with name _Array_.
*/
/** @pred matlab_set(+ _MatVar_, + _X_, + _Y_, + _Value_)
Call MATLAB to set element _MatVar_( _X_, _Y_) to
_Value_. Notice that this command uses the MATLAB array access
convention.
*/
/** @pred matlab_vector(+ _Size_, + _List_, ? _Array_)
MATLAB will create a vector of floats of size _Size_, initialized
from the list _List_, and if _Array_ is bound to an atom,
store the array in the matlab variable with name _Array_.
*/
/** @pred matlab_zeros(+ _SizeX_, + _SizeY_, + _SizeZ_, ? _Array_)
MATLAB will create an array of zeros of size _SizeX_, _SizeY_,
and _SizeZ_. If _Array_ is bound to an atom, store the array
in the matlab variable with name _Array_. Corresponds to the
MATLAB command `zeros`.
*/
/** @pred matlab_zeros(+ _SizeX_, + _SizeY_, ? _Array_)
MATLAB will create an array of zeros of size _SizeX_ and
_SizeY_, and if _Array_ is bound to an atom, store the array
in the matlab variable with name _Array_. Corresponds to the
MATLAB command `zeros`.
*/
/** @pred matlab_zeros(+ _Size_, ? _Array_)
MATLAB will create a vector of zeros of size _Size_, and if
_Array_ is bound to an atom, store the array in the matlab
variable with name _Array_. Corresponds to the MATLAB command
`zeros`.
*/
:- module(matlab,
[start_matlab/1,
close_matlab/0,

View File

@ -15,6 +15,102 @@
* *
*************************************************************************/
/** @defgroup matrix Matrix Library
@ingroup YAPLibrary
@{
This package provides a fast implementation of multi-dimensional
matrices of integers and floats. In contrast to dynamic arrays, these
matrices are multi-dimensional and compact. In contrast to static
arrays. these arrays are allocated in the stack. Matrices are available
by loading the library `library(matrix)`. They are multimensional
objects of type:
+ <tt>terms</tt>: Prolog terms
+ <tt>ints</tt>: bounded integers, represented as an opaque term. The
maximum integer depends on hardware, but should be obtained from the
natural size of the machine.
+ <tt>floats</tt>: floating-poiny numbers, represented as an opaque term.
Matrix elements can be accessed through the `matrix_get/2`
predicate or through an <tt>R</tt>-inspired access notation (that uses the ciao
style extension to `[]`. Examples include:
+ Access the second row, third column of matrix <tt>X</tt>. Indices start from
`0`,
~~~~
_E_ <== _X_[2,3]
~~~~
+ Access all the second row, the output is a list ofe elements.
~~~~
_L_ <== _X_[2,_]
~~~~
+ Access all the second, thrd and fourth rows, the output is a list of elements.
~~~~
_L_ <== _X_[2..4,_]
~~~~
+ Access all the fifth, sixth and eight rows, the output is a list of elements.
~~~~
_L_ <== _X_[2..4+3,_]
~~~~
The matrix library also supports a B-Prolog/ECliPSe inspired `foreach`iterator to iterate over
elements of a matrix:
+ Copy a vector, element by element.
~~~~
foreach(I in 0..N1, X[I] <== Y[I])
~~~~
+ The lower-triangular matrix _Z_ is the difference between the
lower-triangular and upper-triangular parts of _X_.
~~~~
foreach([I in 0..N1, J in I..N1], Z[I,J] <== X[I,J] - X[I,J])
~~~~
+ Add all elements of a matrix by using _Sum_ as an accumulator.
~~~~
foreach([I in 0..N1, J in 0..N1], plus(X[I,J]), 0, Sum)
~~~~
Notice that the library does not support all known matrix operations. Please
contact the YAP maintainers if you require extra functionality.
+ _X_ = array[ _Dim1_,..., _Dimn_] of _Objects_
The of/2 operator can be used to create a new array of
_Objects_. The objects supported are:
+ `Unbound Variable`
create an array of free variables
+ `ints `
create an array of integers
+ `floats `
create an array of floating-point numbers
+ `_I_: _J_`
create an array with integers from _I_ to _J_
+ `[..]`
create an array from the values in a list
The dimensions can be given as an integer, and the matrix will be
indexed `C`-style from `0..( _Max_-1)`, or can be given
as an interval ` _Base_.. _Limit_`. In the latter case,
matrices of integers and of floating-point numbers should have the same
_Base_ on every dimension.
*/
/*
A matrix is an object with integer or floating point numbers. A matrix
may have a number of dimensions. These routines implement a number of
@ -37,6 +133,438 @@ typedef enum {
*/
/** @pred ?_LHS_ <== ?_RHS_ is semidet
General matrix assignment operation. It evaluates the right-hand side
and then acts different according to the
left-hand side and to the matrix:
+ if _LHS_ is part of an integer or floating-point matrix,
perform non-backtrackable assignment.
+ other unify left-hand side and right-hand size.
The right-hand side supports the following operators:
+ `[]/2`
written as _M_[ _Offset_]: obtain an element or list of elements
of matrix _M_ at offset _Offset_.
+ `matrix/1`
create a vector from a list
+ `matrix/2`
create a matrix from a list. Options are:
+ dim=
a list of dimensions
+ type=
integers, floating-point or terms
+ base=
a list of base offsets per dimension (all must be the same for arrays of
integers and floating-points
+ `matrix/3`
create matrix giving two options
+ `dim/1`
list with matrix dimensions
+ `nrow/1`
number of rows in bi-dimensional matrix
+ `ncol/1`
number of columns in bi-dimensional matrix
+ `length/1`
size of a matrix
+ `size/1`
size of a matrix
+ `max/1`
maximum element of a numeric matrix
+ `maxarg/1`
argument of maximum element of a numeric matrix
+ `min/1`
minimum element of a numeric matrix
+ `minarg/1`
argument of minimum element of a numeric matrix
+ `list/1`
represent matrix as a list
+ `lists/2`
represent matrix as list of embedded lists
+ `../2`
_I_.. _J_ generates a list with all integers from _I_ to
_J_, included.
+ `+/2`
add two numbers, add two matrices element-by-element, or add a number to
all elements of a matrix or list.
+ `-/2 `
subtract two numbers, subtract two matrices or lists element-by-element, or subtract a number from
all elements of a matrix or list
+ `* /2`
multiply two numbers, multiply two matrices or lists element-by-element, or multiply a number from
all elements of a matrix or list
+ `log/1`
natural logarithm of a number, matrix or list
+ `exp/1 `
natural exponentiation of a number, matrix or list
*/
/** @pred matrix_add(+ _Matrix_,+ _Position_,+ _Operand_)
Add _Operand_ to the element of _Matrix_ at position
_Position_.
*/
/** @pred matrix_agg_cols(+ _Matrix_,+Operator,+ _Aggregate_)
If _Matrix_ is a n-dimensional matrix, unify _Aggregate_ with
the one dimensional matrix where each element is obtained by adding all
Matrix elements with same first index. Currently, only addition is supported.
*/
/** @pred matrix_agg_lines(+ _Matrix_,+Operator,+ _Aggregate_)
If _Matrix_ is a n-dimensional matrix, unify _Aggregate_ with
the n-1 dimensional matrix where each element is obtained by adding all
_Matrix_ elements with same last n-1 index. Currently, only addition is supported.
*/
/** @pred matrix_arg_to_offset(+ _Matrix_,+ _Position_,- _Offset_)
Given matrix _Matrix_ return what is the numerical _Offset_ of
the element at _Position_.
*/
/** @pred matrix_column(+ _Matrix_,+ _Column_,- _NewMatrix_)
Select from _Matrix_ the column matching _Column_ as new matrix _NewMatrix_. _Column_ must have one less dimension than the original matrix.
*/
/** @pred matrix_dec(+ _Matrix_,+ _Position_)
Decrement the element of _Matrix_ at position _Position_.
*/
/** @pred matrix_dec(+ _Matrix_,+ _Position_,- _Element_)
Decrement the element of _Matrix_ at position _Position_ and
unify with _Element_.
*/
/** @pred matrix_dims(+ _Matrix_,- _Dims_)
Unify _Dims_ with a list of dimensions for _Matrix_.
*/
/** @pred matrix_expand(+ _Matrix_,+ _NewDimensions_,- _New_)
Expand _Matrix_ to occupy new dimensions. The elements in
_NewDimensions_ are either 0, for an existing dimension, or a
positive integer with the size of the new dimension.
*/
/** @pred matrix_get(+ _Matrix_,+ _Position_,- _Elem_)
Unify _Elem_ with the element of _Matrix_ at position
_Position_.
*/
/** @pred matrix_get(+ _Matrix_[+ _Position_],- _Elem_)
Unify _Elem_ with the element _Matrix_[ _Position_].
*/
/** @pred matrix_inc(+ _Matrix_,+ _Position_)
Increment the element of _Matrix_ at position _Position_.
*/
/** @pred matrix_inc(+ _Matrix_,+ _Position_,- _Element_)
Increment the element of _Matrix_ at position _Position_ and
unify with _Element_.
*/
/** @pred matrix_max(+ _Matrix_,+ _Max_)
Unify _Max_ with the maximum in matrix _Matrix_.
*/
/** @pred matrix_maxarg(+ _Matrix_,+ _Maxarg_)
Unify _Max_ with the position of the maximum in matrix _Matrix_.
*/
/** @pred matrix_min(+ _Matrix_,+ _Min_)
Unify _Min_ with the minimum in matrix _Matrix_.
*/
/** @pred matrix_minarg(+ _Matrix_,+ _Minarg_)
Unify _Min_ with the position of the minimum in matrix _Matrix_.
*/
/** @pred matrix_ndims(+ _Matrix_,- _Dims_)
Unify _NDims_ with the number of dimensions for _Matrix_.
*/
/** @pred matrix_new(+ _Type_,+ _Dims_,+ _List_,- _Matrix_)
Create a new matrix _Matrix_ of type _Type_, which may be one of
`ints` or `floats`, with dimensions _Dims_, and
initialised from list _List_.
*/
/** @pred matrix_new(+ _Type_,+ _Dims_,- _Matrix_)
Create a new matrix _Matrix_ of type _Type_, which may be one of
`ints` or `floats`, and with a list of dimensions _Dims_.
The matrix will be initialised to zeros.
~~~~~
?- matrix_new(ints,[2,3],Matrix).
Matrix = {..}
~~~~~
Notice that currently YAP will always write a matrix of numbers as `{..}`.
*/
/** @pred matrix_new_set(? _Dims_,+ _OldMatrix_,+ _Value_,- _NewMatrix_)
Create a new matrix _NewMatrix_ of type _Type_, with dimensions
_Dims_. The elements of _NewMatrix_ are set to _Value_.
*/
/** @pred matrix_offset_to_arg(+ _Matrix_,- _Offset_,+ _Position_)
Given a position _Position _ for matrix _Matrix_ return the
corresponding numerical _Offset_ from the beginning of the matrix.
*/
/** @pred matrix_op(+ _Matrix1_,+ _Matrix2_,+ _Op_,- _Result_)
_Result_ is the result of applying _Op_ to matrix _Matrix1_
and _Matrix2_. Currently, only addition (`+`) is supported.
*/
/** @pred matrix_op_to_all(+ _Matrix1_,+ _Op_,+ _Operand_,- _Result_)
_Result_ is the result of applying _Op_ to all elements of
_Matrix1_, with _Operand_ as the second argument. Currently,
only addition (`+`), multiplication (`\*`), and division
(`/`) are supported.
*/
/** @pred matrix_op_to_cols(+ _Matrix1_,+ _Cols_,+ _Op_,- _Result_)
_Result_ is the result of applying _Op_ to all elements of
_Matrix1_, with the corresponding element in _Cols_ as the
second argument. Currently, only addition (`+`) is
supported. Notice that _Cols_ will have n-1 dimensions.
*/
/** @pred matrix_op_to_lines(+ _Matrix1_,+ _Lines_,+ _Op_,- _Result_)
_Result_ is the result of applying _Op_ to all elements of
_Matrix1_, with the corresponding element in _Lines_ as the
second argument. Currently, only division (`/`) is supported.
*/
/** @pred matrix_select(+ _Matrix_,+ _Dimension_,+ _Index_,- _New_)
Select from _Matrix_ the elements who have _Index_ at
_Dimension_.
*/
/** @pred matrix_set(+ _Matrix_,+ _Position_,+ _Elem_)
Set the element of _Matrix_ at position
_Position_ to _Elem_.
*/
/** @pred matrix_set(+ _Matrix_[+ _Position_],+ _Elem_)
Set the element of _Matrix_[ _Position_] to _Elem_.
*/
/** @pred matrix_set_all(+ _Matrix_,+ _Elem_)
Set all element of _Matrix_ to _Elem_.
*/
/** @pred matrix_shuffle(+ _Matrix_,+ _NewOrder_,- _Shuffle_)
Shuffle the dimensions of matrix _Matrix_ according to
_NewOrder_. The list _NewOrder_ must have all the dimensions of
_Matrix_, starting from 0.
*/
/** @pred matrix_size(+ _Matrix_,- _NElems_)
Unify _NElems_ with the number of elements for _Matrix_.
*/
/** @pred matrix_sum(+ _Matrix_,+ _Sum_)
Unify _Sum_ with the sum of all elements in matrix _Matrix_.
*/
/** @pred matrix_to_list(+ _Matrix_,- _Elems_)
Unify _Elems_ with the list including all the elements in _Matrix_.
*/
/** @pred matrix_transpose(+ _Matrix_,- _Transpose_)
Transpose matrix _Matrix_ to _Transpose_. Equivalent to:
~~~~~
matrix_transpose(Matrix,Transpose) :-
matrix_shuffle(Matrix,[1,0],Transpose).
~~~~~
*/
/** @pred matrix_type(+ _Matrix_,- _Type_)
Unify _NElems_ with the type of the elements in _Matrix_.
*/
:- module( matrix,
[op(100, yf, []),
(<==)/2, op(600, xfx, '<=='),

View File

@ -15,6 +15,179 @@
* *
*************************************************************************/
/** @defgroup NonhYBacktrackable_Data_Structures Non-Backtrackable Data Structures
@ingroup YAPLibrary
@{
The following routines implement well-known data-structures using global
non-backtrackable variables (implemented on the Prolog stack). The
data-structures currently supported are Queues, Heaps, and Beam for Beam
search. They are allowed through `library(nb)`.
*/
/** @pred nb_beam(+ _DefaultSize_,- _Beam_)
Create a _Beam_ with default size _DefaultSize_. Note that size
is fixed throughout.
*/
/** @pred nb_beam_add(+ _Beam_, + _Key_, + _Value_)
Add _Key_- _Value_ to the beam _Beam_. The key is sorted on
_Key_ only.
*/
/** @pred nb_beam_close(+ _Beam_)
Close the beam _Beam_: no further elements can be added.
*/
/** @pred nb_beam_del(+ _Beam_, - _Key_, - _Value_)
Remove element _Key_- _Value_ with smallest _Value_ in beam
_Beam_. Fail if the beam is empty.
*/
/** @pred nb_beam_empty(+ _Beam_)
Succeeds if _Beam_ is empty.
*/
/** @pred nb_beam_peek(+ _Beam_, - _Key_, - _Value_))
_Key_- _Value_ is the element with smallest _Key_ in the beam
_Beam_. Fail if the beam is empty.
*/
/** @pred nb_beam_size(+ _Beam_, - _Size_)
Unify _Size_ with the number of elements in the beam _Beam_.
*/
/** @pred nb_heap(+ _DefaultSize_,- _Heap_)
Create a _Heap_ with default size _DefaultSize_. Note that size
will expand as needed.
*/
/** @pred nb_heap_add(+ _Heap_, + _Key_, + _Value_)
Add _Key_- _Value_ to the heap _Heap_. The key is sorted on
_Key_ only.
*/
/** @pred nb_heap_close(+ _Heap_)
Close the heap _Heap_: no further elements can be added.
*/
/** @pred nb_heap_del(+ _Heap_, - _Key_, - _Value_)
Remove element _Key_- _Value_ with smallest _Value_ in heap
_Heap_. Fail if the heap is empty.
*/
/** @pred nb_heap_empty(+ _Heap_)
Succeeds if _Heap_ is empty.
*/
/** @pred nb_heap_peek(+ _Heap_, - _Key_, - _Value_))
_Key_- _Value_ is the element with smallest _Key_ in the heap
_Heap_. Fail if the heap is empty.
*/
/** @pred nb_heap_size(+ _Heap_, - _Size_)
Unify _Size_ with the number of elements in the heap _Heap_.
*/
/** @pred nb_queue(- _Queue_)
Create a _Queue_.
*/
/** @pred nb_queue_close(+ _Queue_, - _Head_, ? _Tail_)
Unify the queue _Queue_ with a difference list
_Head_- _Tail_. The queue will now be empty and no further
elements can be added.
*/
/** @pred nb_queue_dequeue(+ _Queue_, - _Element_)
Remove _Element_ from the front of the queue _Queue_. Fail if
the queue is empty.
*/
/** @pred nb_queue_empty(+ _Queue_)
Succeeds if _Queue_ is empty.
*/
/** @pred nb_queue_enqueue(+ _Queue_, + _Element_)
Add _Element_ to the front of the queue _Queue_.
*/
/** @pred nb_queue_peek(+ _Queue_, - _Element_)
_Element_ is the front of the queue _Queue_. Fail if
the queue is empty.
*/
/** @pred nb_queue_size(+ _Queue_, - _Size_)
Unify _Size_ with the number of elements in the queue _Queue_.
*/
:- module(nb, [
nb_create_accumulator/2,
nb_add_to_accumulator/2,

View File

@ -17,6 +17,162 @@
% unchanged. The main difficulty with the ordered representation is
% remembering to use it!
/** @defgroup Ordered_Sets Ordered Sets
@ingroup YAPLibrary
@{
The following ordered set manipulation routines are available once
included with the `use_module(library(ordsets))` command. An
ordered set is represented by a list having unique and ordered
elements. Output arguments are guaranteed to be ordered sets, if the
relevant inputs are. This is a slightly patched version of Richard
O'Keefe's original library.
*/
/** @pred list_to_ord_set(+ _List_, ? _Set_)
Holds when _Set_ is the ordered representation of the set
represented by the unordered representation _List_.
*/
/** @pred merge(+ _List1_, + _List2_, - _Merged_)
Holds when _Merged_ is the stable merge of the two given lists.
Notice that merge/3 will not remove duplicates, so merging
ordered sets will not necessarily result in an ordered set. Use
`ord_union/3` instead.
*/
/** @pred ord_add_element(+ _Set1_, + _Element_, ? _Set2_)
Inserting _Element_ in _Set1_ returns _Set2_. It should give
exactly the same result as `merge(Set1, [Element], Set2)`, but a
bit faster, and certainly more clearly. The same as ord_insert/3.
*/
/** @pred ord_del_element(+ _Set1_, + _Element_, ? _Set2_)
Removing _Element_ from _Set1_ returns _Set2_.
*/
/** @pred ord_disjoint(+ _Set1_, + _Set2_)
Holds when the two ordered sets have no element in common.
*/
/** @pred ord_insert(+ _Set1_, + _Element_, ? _Set2_)
Inserting _Element_ in _Set1_ returns _Set2_. It should give
exactly the same result as `merge(Set1, [Element], Set2)`, but a
bit faster, and certainly more clearly. The same as ord_add_element/3.
*/
/** @pred ord_intersect(+ _Set1_, + _Set2_)
Holds when the two ordered sets have at least one element in common.
*/
/** @pred ord_intersection(+ _Set1_, + _Set2_, ? _Intersection_)
Holds when Intersection is the ordered representation of _Set1_
and _Set2_.
*/
/** @pred ord_intersection(+ _Set1_, + _Set2_, ? _Intersection_, ? _Diff_)
Holds when Intersection is the ordered representation of _Set1_
and _Set2_. _Diff_ is the difference between _Set2_ and _Set1_.
*/
/** @pred ord_member(+ _Element_, + _Set_)
Holds when _Element_ is a member of _Set_.
*/
/** @pred ord_seteq(+ _Set1_, + _Set2_)
Holds when the two arguments represent the same set.
*/
/** @pred ord_setproduct(+ _Set1_, + _Set2_, - _Set_)
If Set1 and Set2 are ordered sets, Product will be an ordered
set of x1-x2 pairs.
*/
/** @pred ord_subset(+ _Set1_, + _Set2_)
Holds when every element of the ordered set _Set1_ appears in the
ordered set _Set2_.
*/
/** @pred ord_subtract(+ _Set1_, + _Set2_, ? _Difference_)
Holds when _Difference_ contains all and only the elements of _Set1_
which are not also in _Set2_.
*/
/** @pred ord_symdiff(+ _Set1_, + _Set2_, ? _Difference_)
Holds when _Difference_ is the symmetric difference of _Set1_
and _Set2_.
*/
/** @pred ord_union(+ _Set1_, + _Set2_, ? _Union_)
Holds when _Union_ is the union of _Set1_ and _Set2_.
*/
/** @pred ord_union(+ _Set1_, + _Set2_, ? _Union_, ? _Diff_)
Holds when _Union_ is the union of _Set1_ and _Set2_ and
_Diff_ is the difference.
*/
/** @pred ord_union(+ _Sets_, ? _Union_)
Holds when _Union_ is the union of the lists _Sets_.
*/
:- module(ordsets, [
list_to_ord_set/2, % List -> Set
merge/3, % OrdList x OrdList -> OrdList

View File

@ -43,6 +43,47 @@
% Its drawback is the lack of randomness of low-order bits.
/** @pred rannum(- _I_)
Produces a random non-negative integer _I_ whose low bits are not
all that random, so it should be scaled to a smaller range in general.
The integer _I_ is in the range 0 .. 2^(w-1) - 1. You can use:
~~~~~
rannum(X) :- yap_flag(max_integer,MI), rannum(R), X is R/MI.
~~~~~
to obtain a floating point number uniformly distributed between 0 and 1.
*/
/** @pred ranstart
Initialize the random number generator using a built-in seed. The
ranstart/0 built-in is always called by the system when loading
the package.
*/
/** @pred ranstart(+ _Seed_)
Initialize the random number generator with user-defined _Seed_. The
same _Seed_ always produces the same sequence of numbers.
*/
/** @pred ranunif(+ _Range_,- _I_)
ranunif/2 produces a uniformly distributed non-negative random
integer _I_ over a caller-specified range _R_. If range is _R_,
the result is in 0 .. _R_-1.
*/
:- module(prandom, [
ranstart/0,
ranstart/1,

View File

@ -6,6 +6,99 @@
% Purpose: define queue operations
% Needs : lib(lists) for append/3.
/** @defgroup Queues Queues
@ingroup YAPLibrary
@{
The following queue manipulation routines are available once
included with the `use_module(library(queues))` command. Queues are
implemented with difference lists.
*/
/**
@pred make_queue(+ _Queue_)
Creates a new empty queue. It should only be used to create a new queue.
*/
/** @pred empty_queue(+ _Queue_)
Tests whether the queue is empty.
*/
/** @pred head_queue(+ _Queue_, ? _Head_)
Unifies Head with the first element of the queue.
*/
/** @pred join_queue(+ _Element_, + _OldQueue_, - _NewQueue_)
Adds the new element at the end of the queue.
*/
/** @pred jump_queue(+ _Element_, + _OldQueue_, - _NewQueue_)
Adds the new element at the front of the list.
*/
/** @pred length_queue(+ _Queue_, - _Length_)
Counts the number of elements currently in the queue.
*/
/** @pred list_join_queue(+ _List_, + _OldQueue_, - _NewQueue_)
Ads the new elements at the end of the queue.
*/
/** @pred list_jump_queue(+ _List_, + _OldQueue_, + _NewQueue_)
Adds all the elements of _List_ at the front of the queue.
*/
/** @pred list_to_queue(+ _List_, - _Queue_)
Creates a new queue with the same elements as _List._
*/
/** @pred queue_to_list(+ _Queue_, - _List_)
Creates a new list with the same elements as _Queue_.
*/
/** @pred serve_queue(+ _OldQueue_, + _Head_, - _NewQueue_)
Removes the first element of the queue for service.
*/
:- module(queues, [
make_queue/1, % create empty queue
join_queue/3, % add element to end of queue

View File

@ -22,6 +22,88 @@
% version which yields 15-bit random integers using only integer
% arithmetic.
/** @defgroup Random Random Number Generator
@ingroup YAPLibrary
@{
The following random number operations are included with the
`use_module(library(random))` command. Since YAP-4.3.19 YAP uses
the O'Keefe public-domain algorithm, based on the "Applied Statistics"
algorithm AS183.
@pred getrand(- _Key_)
Unify _Key_ with a term of the form `rand(X,Y,Z)` describing the
current state of the random number generator.
*/
/** @pred random(+ _LOW_, + _HIGH_, - _NUMBER_)
Unify _Number_ with a number in the range
`[LOW...HIGH)`. If both _LOW_ and _HIGH_ are
integers then _NUMBER_ will also be an integer, otherwise
_NUMBER_ will be a floating-point number.
*/
/** @defgroup Pseudo_Random Pseudo Random Number Integer Generator
@ingroup YAPLibrary
@{
The following routines produce random non-negative integers in the range
0 .. 2^(w-1) -1, where w is the word size available for integers, e.g.
32 for Intel machines and 64 for Alpha machines. Note that the numbers
generated by this random number generator are repeatable. This generator
was originally written by Allen Van Gelder and is based on Knuth Vol 2.
*/
/** @pred random(- _Number_)
Unify _Number_ with a floating-point number in the range `[0...1)`.
*/
/** @pred randseq(+ _LENGTH_, + _MAX_, - _Numbers_)
Unify _Numbers_ with a list of _LENGTH_ unique random integers
in the range `[1... _MAX_)`.
*/
/** @pred randset(+ _LENGTH_, + _MAX_, - _Numbers_)
Unify _Numbers_ with an ordered list of _LENGTH_ unique random
integers in the range `[1... _MAX_)`.
*/
/** @pred setrand(+ _Key_)
Use a term of the form `rand(X,Y,Z)` to set a new state for the
random number generator. The integer `X` must be in the range
`[1...30269)`, the integer `Y` must be in the range
`[1...30307)`, and the integer `Z` must be in the range
`[1...30323)`.
*/
:- module(random, [
random/1,
random/3,

View File

@ -50,7 +50,9 @@
rb_in/3
]).
/** <module> Red black trees
/** @defgroup RedhYBlack_Trees Red-Black Trees
@ingroup YAPLibrary
@{
Red-Black trees are balanced search binary trees. They are named because
nodes can be classified as either red or black. The code we include is
@ -1228,3 +1230,225 @@ build_ntree(X1,X,T0,TF) :-
/** @pred is_rbtree(+ _T_)
Check whether _T_ is a valid red-black tree.
*/
/** @pred ord_list_to_rbtree(+ _L_, - _T_)
_T_ is the red-black tree corresponding to the mapping in ordered
list _L_.
*/
/** @pred rb_apply(+ _T_,+ _Key_,+ _G_,- _TN_)
If the value associated with key _Key_ is _Val0_ in _T_, and
if `call(G,Val0,ValF)` holds, then _TN_ differs from
_T_ only in that _Key_ is associated with value _ValF_ in
tree _TN_. Fails if it cannot find _Key_ in _T_, or if
`call(G,Val0,ValF)` is not satisfiable.
*/
/** @pred rb_clone(+ _T_,+ _NT_,+ _Nodes_)
=Clone= the red-back tree into a new tree with the same keys as the
original but with all values set to unbound values. _Nodes_ is a list
containing all new nodes as pairs _K-V_.
*/
/** @pred rb_del_max(+ _T_,- _Key_,- _Val_,- _TN_)
Delete the largest element from the tree _T_, returning the key
_Key_, the value _Val_ associated with the key and a new tree
_TN_.
*/
/** @pred rb_del_min(+ _T_,- _Key_,- _Val_,- _TN_)
Delete the least element from the tree _T_, returning the key
_Key_, the value _Val_ associated with the key and a new tree
_TN_.
*/
/** @pred rb_delete(+ _T_,+ _Key_,- _TN_)
Delete element with key _Key_ from the tree _T_, returning a new
tree _TN_.
*/
/** @pred rb_delete(+ _T_,+ _Key_,- _Val_,- _TN_)
Delete element with key _Key_ from the tree _T_, returning the
value _Val_ associated with the key and a new tree _TN_.
*/
/** @pred rb_empty(? _T_)
Succeeds if tree _T_ is empty.
*/
/** @pred rb_fold(+ _T_,+ _G_,+ _Acc0_, - _AccF_)
For all nodes _Key_ in the tree _T_, if the value
associated with key _Key_ is _V_ in tree _T_, if
`call(G,V,Acc1,Acc2)` holds, then if _VL_ is value of the
previous node in inorder, `call(G,VL,_,Acc0)` must hold, and if
_VR_ is the value of the next node in inorder,
`call(G,VR,Acc1,_)` must hold.
*/
/** @pred rb_insert(+ _T0_,+ _Key_,? _Value_,+ _TF_)
Add an element with key _Key_ and _Value_ to the tree
_T0_ creating a new red-black tree _TF_. Duplicated elements are not
allowed.
Add a new element with key _Key_ and _Value_ to the tree
_T0_ creating a new red-black tree _TF_. Fails is an element
with _Key_ exists in the tree.
*/
/** @pred rb_key_fold(+ _T_,+ _G_,+ _Acc0_, - _AccF_)
For all nodes _Key_ in the tree _T_, if the value
associated with key _Key_ is _V_ in tree _T_, if
`call(G,Key,V,Acc1,Acc2)` holds, then if _VL_ is value of the
previous node in inorder, `call(G,KeyL,VL,_,Acc0)` must hold, and if
_VR_ is the value of the next node in inorder,
`call(G,KeyR,VR,Acc1,_)` must hold.
*/
/** @pred rb_keys(+ _T_,+ _Keys_)
_Keys_ is an infix visit with all keys in tree _T_. Keys will be
sorted, but may be duplicate.
*/
/** @pred rb_lookup(+ _Key_,- _Value_,+ _T_)
Backtrack through all elements with key _Key_ in the red-black tree
_T_, returning for each the value _Value_.
*/
/** @pred rb_lookupall(+ _Key_,- _Value_,+ _T_)
Lookup all elements with key _Key_ in the red-black tree
_T_, returning the value _Value_.
*/
/** @pred rb_map(+ _T_,+ _G_,- _TN_)
For all nodes _Key_ in the tree _T_, if the value associated with
key _Key_ is _Val0_ in tree _T_, and if
`call(G,Val0,ValF)` holds, then the value associated with _Key_
in _TN_ is _ValF_. Fails if or if `call(G,Val0,ValF)` is not
satisfiable for all _Var0_.
*/
/** @pred rb_max(+ _T_,- _Key_,- _Value_)
_Key_ is the maximal key in _T_, and is associated with _Val_.
*/
/** @pred rb_min(+ _T_,- _Key_,- _Value_)
_Key_ is the minimum key in _T_, and is associated with _Val_.
*/
/** @pred rb_new(? _T_)
Create a new tree.
*/
/** @pred rb_next(+ _T_, + _Key_,- _Next_,- _Value_)
_Next_ is the next element after _Key_ in _T_, and is
associated with _Val_.
*/
/** @pred rb_partial_map(+ _T_,+ _Keys_,+ _G_,- _TN_)
For all nodes _Key_ in _Keys_, if the value associated with key
_Key_ is _Val0_ in tree _T_, and if `call(G,Val0,ValF)`
holds, then the value associated with _Key_ in _TN_ is
_ValF_. Fails if or if `call(G,Val0,ValF)` is not satisfiable
for all _Var0_. Assumes keys are not repeated.
*/
/** @pred rb_previous(+ _T_, + _Key_,- _Previous_,- _Value_)
_Previous_ is the previous element after _Key_ in _T_, and is
associated with _Val_.
*/
/** @pred rb_size(+ _T_,- _Size_)
_Size_ is the number of elements in _T_.
*/
/** @pred rb_update(+ _T_,+ _Key_,+ _NewVal_,- _TN_)
Tree _TN_ is tree _T_, but with value for _Key_ associated
with _NewVal_. Fails if it cannot find _Key_ in _T_.
*/
/** @pred rb_visit(+ _T_,- _Pairs_)
_Pairs_ is an infix visit of tree _T_, where each element of
_Pairs_ is of the form _K_- _Val_.
@}
*/

View File

@ -15,6 +15,138 @@
* *
*************************************************************************/
/** @defgroup RegExp Regular Expressions
@ingroup YAPLibrary
@{
This library includes routines to determine whether a regular expression
matches part or all of a string. The routines can also return which
parts parts of the string matched the expression or subexpressions of
it. This library relies on Henry Spencer's `C`-package and is only
available in operating systems that support dynamic loading. The
`C`-code has been obtained from the sources of FreeBSD-4.0 and is
protected by copyright from Henry Spencer and from the Regents of the
University of California (see the file library/regex/COPYRIGHT for
further details).
Much of the description of regular expressions below is copied verbatim
from Henry Spencer's manual page.
A regular expression is zero or more branches, separated by ``|`. It
matches anything that matches one of the branches.
A branch is zero or more pieces, concatenated. It matches a match for
the first, followed by a match for the second, etc.
A piece is an atom possibly followed by `\*`, `+`, or `?`. An atom
followed by `\*` matches a sequence of 0 or more matches of the atom.
An atom followed by `+` matches a sequence of 1 or more matches of the
atom. An atom followed by `?` matches a match of the atom, or the
null string.
An atom is a regular expression in parentheses (matching a match for the
regular expression), a range (see below), `.` (matching any single
character), `^` (matching the null string at the beginning of the
input string), `$` (matching the null string at the end of the input
string), a `\` followed by a single character (matching that
character), or a single character with no other significance (matching
that character).
A range is a sequence of characters enclosed in `[]`. It normally
matches any single character from the sequence. If the sequence begins
with `^`, it matches any single character not from the rest of the
sequence. If two characters in the sequence are separated by `-`,
this is shorthand for the full list of ASCII characters between them
(e.g. `[0-9]` matches any decimal digit). To include a literal `]`
in the sequence, make it the first character (following a possible
`^`). To include a literal `-`, make it the first or last
character.
@pred regexp(+ _RegExp_,+ _String_,+ _Opts_)
Match regular expression _RegExp_ to input string _String_
according to options _Opts_. The options may be:
+ `nocase`: Causes upper-case characters in _String_ to
be treated as lower case during the matching process.
*/
/** @pred regexp(+ _RegExp_,+ _String_,+ _Opts_,? _SubMatchVars_)
Match regular expression _RegExp_ to input string _String_
according to options _Opts_. The variable _SubMatchVars_ should
be originally unbound or a list of unbound variables all will contain a
sequence of matches, that is, the head of _SubMatchVars_ will
contain the characters in _String_ that matched the leftmost
parenthesized subexpression within _RegExp_, the next head of list
will contain the characters that matched the next parenthesized
subexpression to the right in _RegExp_, and so on.
The options may be:
+ `nocase`: Causes upper-case characters in _String_ to
be treated as lower case during the matching process.
+ `indices`: Changes what is stored in
_SubMatchVars_. Instead of storing the matching characters from
_String_, each variable will contain a term of the form _IO-IF_
giving the indices in _String_ of the first and last characters in
the matching range of characters.
In general there may be more than one way to match a regular expression
to an input string. For example, consider the command
~~~~~
regexp("(a*)b*","aabaaabb", [], [X,Y])
~~~~~
Considering only the rules given so far, _X_ and _Y_ could end up
with the values `"aabb"` and `"aa"`, `"aaab"` and
`"aaa"`, `"ab"` and `"a"`, or any of several other
combinations. To resolve this potential ambiguity `regexp` chooses among
alternatives using the rule `first then longest`. In other words, it
considers the possible matches in order working from left to right
across the input string and the pattern, and it attempts to match longer
pieces of the input string before shorter ones. More specifically, the
following rules apply in decreasing order of priority:
+ If a regular expression could match two different parts of an
input string then it will match the one that begins earliest.
+ If a regular expression contains "|" operators then the leftmost matching sub-expression is chosen.
+ In \*, +, and ? constructs, longer matches are chosen in preference to shorter ones.
+ In sequences of expression components the components are considered from left to right.
In the example above, `"(a\*)b\*"` matches `"aab"`: the
`"(a\*)"` portion of the pattern is matched first and it consumes
the leading `"aa"`; then the `"b\*"` portion of the pattern
consumes the next `"b"`. Or, consider the following example:
~~~~~
regexp("(ab|a)(b*)c", "abc", [], [X,Y,Z])
~~~~~
After this command _X_ will be `"abc"`, _Y_ will be
`"ab"`, and _Z_ will be an empty string. Rule 4 specifies that
`"(ab|a)"` gets first shot at the input string and Rule 2 specifies
that the `"ab"` sub-expression is checked before the `"a"`
sub-expression. Thus the `"b"` has already been claimed before the
`"(b\*)"` component is checked and `(b\*)` must match an empty string.
*/
:- module(regexp, [
regexp/3,
regexp/4

View File

@ -2,12 +2,101 @@
<module> SICStus compatible socket library
@ingroup YAPBuiltins
YAP includes a SICStus Prolog compatible socket interface. In YAP-6.3
this uses the `clib` package to emulate the old low level interface that
provides direct access to the major socket system calls. These calls
can be used both to open a new connection in the network or connect to
a networked server. Socket connections are described as read/write
streams, and standard Input/Output built-ins can be used to write on or read
from sockets. The following calls are available:
@tbd Our implementation does not support AF_UNIX sockets.
@TBD Implement socket_select/5
@see http://www.sics.se/sicstus/docs/3.7.1/html/sicstus_28.html
*/
/** @pred current_host(? _HOSTNAME_)
Unify _HOSTNAME_ with an atom representing the fully qualified
hostname for the current host. Also succeeds if _HOSTNAME_ is bound
to the unqualified hostname.
*/
/** @pred hostname_address(? _HOSTNAME_,? _IP_ADDRESS_)
_HOSTNAME_ is an host name and _IP_ADDRESS_ its IP
address in number and dots notation.
*/
/** @pred socket_accept(+ _SOCKET_, - _CLIENT_, - _STREAM_)
Interface to system call `accept`, used for servers to wait for
connections at socket _SOCKET_. The stream descriptor _STREAM_
represents the resulting connection. If the socket belongs to the
domain `AF_INET`, _CLIENT_ unifies with an atom containing
the IP address for the client in numbers and dots notation.
*/
/** @pred socket_accept(+ _SOCKET_, - _STREAM_)
Accept a connection but do not return client information.
*/
/** @pred socket_bind(+ _SOCKET_, ? _PORT_)
Interface to system call `bind`, as used for servers: bind socket
to a port. Port information depends on the domain:
+ 'AF_UNIX'(+ _FILENAME_) (unsupported)
+ 'AF_FILE'(+ _FILENAME_)
use file name _FILENAME_ for UNIX or local sockets.
+ 'AF_INET'(? _HOST_,?PORT)
If _HOST_ is bound to an atom, bind to host _HOST_, otherwise
if unbound bind to local host ( _HOST_ remains unbound). If port
_PORT_ is bound to an integer, try to bind to the corresponding
port. If variable _PORT_ is unbound allow operating systems to
choose a port number, which is unified with _PORT_.
*/
/** @pred socket_close(+ _SOCKET_)
Close socket _SOCKET_. Note that sockets used in
`socket_connect` (that is, client sockets) should not be closed with
`socket_close`, as they will be automatically closed when the
corresponding stream is closed with close/1 or `close/2`.
*/
/** @pred socket_listen(+ _SOCKET_, + _LENGTH_)
Interface to system call `listen`, used for servers to indicate
willingness to wait for connections at socket _SOCKET_. The
integer _LENGTH_ gives the queue limit for incoming connections,
and should be limited to `5` for portable applications. The socket
must be of type `SOCK_STREAM` or `SOCK_SEQPACKET`.
*/
:- module(yap_sockets,
[ ip_socket/2, % +Domain, -Socket
ip_socket/4, % +Domain, +Type, +Protocol, -Socket
@ -77,6 +166,16 @@ socket_accept(Socket, Client, StreamPair) :-
tcp_open_socket(Socket2, Read, Write),
stream_pair(StreamPair, Read, Write).
/** @pred socket_buffering(+ _SOCKET_, - _MODE_, - _OLD_, + _NEW_)
Set buffering for _SOCKET_ in `read` or `write`
_MODE_. _OLD_ is unified with the previous status, and _NEW_
receives the new status which may be one of `unbuf` or
`fullbuf`.
*/
socket_buffering(STREAM, _, CUR, NEW) :-
stream_property(STREAM, buffer(Prop) ),
translate_buffer(Prop, CUR),
@ -103,5 +202,30 @@ peer_to_client(ip(A,B,C,D), Client) :-
maplist(atom_number, Parts, Numbers),
Numbers = [A,B,C,D].
/** @pred socket_select(+ _SOCKETS_, - _NEWSTREAMS_, + _TIMEOUT_, + _STREAMS_, - _READSTREAMS_) [unsupported in YAP-6.3]
Interface to system call `select`, used for servers to wait for
connection requests or for data at sockets. The variable
_SOCKETS_ is a list of form _KEY-SOCKET_, where _KEY_ is
an user-defined identifier and _SOCKET_ is a socket descriptor. The
variable _TIMEOUT_ is either `off`, indicating execution will
wait until something is available, or of the form _SEC-USEC_, where
_SEC_ and _USEC_ give the seconds and microseconds before
socket_select/5 returns. The variable _SOCKETS_ is a list of
form _KEY-STREAM_, where _KEY_ is an user-defined identifier
and _STREAM_ is a stream descriptor
Execution of socket_select/5 unifies _READSTREAMS_ from
_STREAMS_ with readable data, and _NEWSTREAMS_ with a list of
the form _KEY-STREAM_, where _KEY_ was the key for a socket
with pending data, and _STREAM_ the stream descriptor resulting
from accepting the connection.
*/
socket_select(_,_,_,_,_) :-
format( user_error, "Unsupported in this version, please use wait_for_input/3~n", []).
/**
@}
*/

View File

@ -15,6 +15,82 @@
* *
*************************************************************************/
/** @defgroup Splay_Trees Splay Trees
@ingroup YAPLibrary
@{
Splay trees are explained in the paper "Self-adjusting Binary Search
Trees", by D.D. Sleator and R.E. Tarjan, JACM, vol. 32, No.3, July 1985,
p. 668. They are designed to support fast insertions, deletions and
removals in binary search trees without the complexity of traditional
balanced trees. The key idea is to allow the tree to become
unbalanced. To make up for this, whenever we find a node, we move it up
to the top. We use code by Vijay Saraswat originally posted to the Prolog
mailing-list.
@pred splay_access(- _Return_,+ _Key_,? _Val_,+ _Tree_,- _NewTree_)
If item _Key_ is in tree _Tree_, return its _Val_ and
unify _Return_ with `true`. Otherwise unify _Return_ with
`null`. The variable _NewTree_ unifies with the new tree.
*/
/** @pred splay_del(+ _Item_,+ _Tree_,- _NewTree_)
Delete item _Key_ from tree _Tree_, assuming that it is present
already. The variable _Val_ unifies with a value for key _Key_,
and the variable _NewTree_ unifies with the new tree. The predicate
will fail if _Key_ is not present.
*/
/** @pred splay_init(- _NewTree_)
Initialize a new splay tree.
*/
/** @pred splay_insert(+ _Key_,? _Val_,+ _Tree_,- _NewTree_)
Insert item _Key_ in tree _Tree_, assuming that it is not
there already. The variable _Val_ unifies with a value for key
_Key_, and the variable _NewTree_ unifies with the new
tree. In our implementation, _Key_ is not inserted if it is
already there: rather it is unified with the item already in the tree.
*/
/** @pred splay_join(+ _LeftTree_,+ _RighTree_,- _NewTree_)
Combine trees _LeftTree_ and _RighTree_ into a single
tree _NewTree_ containing all items from both trees. This operation
assumes that all items in _LeftTree_ are less than all those in
_RighTree_ and destroys both _LeftTree_ and _RighTree_.
*/
/** @pred splay_split(+ _Key_,? _Val_,+ _Tree_,- _LeftTree_,- _RightTree_)
Construct and return two trees _LeftTree_ and _RightTree_,
where _LeftTree_ contains all items in _Tree_ less than
_Key_, and _RightTree_ contains all items in _Tree_
greater than _Key_. This operations destroys _Tree_.
*/
:- module(splay,[
splay_access/5,
splay_insert/4,
@ -73,7 +149,7 @@
% The basic workhorse is the routine bst(Op, Item, Tree, NewTree), which
% returns in NewTree a binary search tree obtained by searching for Item
% in Tree and splaying. OP controls what must happen if Item is not
% in< Tree and splaying. OP controls what must happen if Item is not
% found in the Tree. If Op = access(V), then V is unified with null if
% the item is not found in the tree, and with true if it is; in the
% latter case Item is also unified with the item found in the tree. In

358
library/system.yap Executable file → Normal file
View File

@ -15,6 +15,364 @@
* *
*************************************************************************/
/** @defgroup System Calling The Operating System from YAP
@ingroup YAPLibrary
@{
YAP now provides a library of system utilities compatible with the
SICStus Prolog system library. This library extends and to some point
replaces the functionality of Operating System access routines. The
library includes Unix/Linux and Win32 `C` code. They
are available through the `use_module(library(system))` command.
@pred datime(datime(- _Year_, - _Month_, - _DayOfTheMonth_, - _Hour_, - _Minute_, - _Second_)
The datime/1 procedure returns the current date and time, with
information on _Year_, _Month_, _DayOfTheMonth_,
_Hour_, _Minute_, and _Second_. The _Hour_ is returned
on local time. This function uses the WIN32
`GetLocalTime` function or the Unix `localtime` function.
~~~~~
?- datime(X).
X = datime(2001,5,28,15,29,46) ?
~~~~~
*/
/** @pred environ(+ _E_,- _S_)
Given an environment variable _E_ this predicate unifies the second argument _S_ with its value.
*/
/** @pred system(+ _S_)
Passes command _S_ to the Bourne shell (on UNIX environments) or the
current command interpreter in WIN32 environments.
*/
/** @pred working_directory(- _CurDir_,? _NextDir_)
Fetch the current directory at _CurDir_. If _NextDir_ is bound
to an atom, make its value the current working directory.
*/
/** @pred delete_file(+ _File_)
The delete_file/1 procedure removes file _File_. If
_File_ is a directory, remove the directory <em>and all its subdirectories</em>.
~~~~~
?- delete_file(x).
~~~~~
*/
/** @pred delete_file(+ _File_,+ _Opts_)
The `delete_file/2` procedure removes file _File_ according to
options _Opts_. These options are `directory` if one should
remove directories, `recursive` if one should remove directories
recursively, and `ignore` if errors are not to be reported.
This example is equivalent to using the delete_file/1 predicate:
~~~~~
?- delete_file(x, [recursive]).
~~~~~
*/
/** @pred directory_files(+ _Dir_,+ _List_)
Given a directory _Dir_, directory_files/2 procedures a
listing of all files and directories in the directory:
~~~~~
?- directory_files('.',L), writeq(L).
['Makefile.~1~','sys.so','Makefile','sys.o',x,..,'.']
~~~~~
The predicates uses the `dirent` family of routines in Unix
environments, and `findfirst` in WIN32.
*/
/** @pred environ(? _EnvVar_,+ _EnvValue_)
Unify environment variable _EnvVar_ with its value _EnvValue_,
if there is one. This predicate is backtrackable in Unix systems, but
not currently in Win32 configurations.
~~~~~
?- environ('HOME',X).
X = 'C:\\cygwin\\home\\administrator' ?
~~~~~
*/
/** @pred exec(+ _Command_, _StandardStreams_,- _PID_)
Execute command _Command_ with its standard streams connected to
the list [_InputStream_, _OutputStream_, _ErrorStream_]. The
process that executes the command is returned as _PID_. The
command is executed by the default shell `bin/sh -c` in Unix.
The following example demonstrates the use of exec/3 to send a
command and process its output:
~~~~~
exec(ls,[std,pipe(S),null],P),repeat, get0(S,C), (C = -1, close(S) ! ; put(C)).
~~~~~
The streams may be one of standard stream, `std`, null stream,
`null`, or `pipe(S)`, where _S_ is a pipe stream. Note
that it is up to the user to close the pipe.
*/
/** @pred file_exists(+ _File_)
The atom _File_ corresponds to an existing file.
*/
/** @pred file_exists(+ _File_,+ _Permissions_)
The atom _File_ corresponds to an existing file with permissions
compatible with _Permissions_. YAP currently only accepts for
permissions to be described as a number. The actual meaning of this
number is Operating System dependent.
*/
/** @pred file_property(+ _File_,? _Property_)
The atom _File_ corresponds to an existing file, and _Property_
will be unified with a property of this file. The properties are of the
form `type( _Type_)`, which gives whether the file is a regular
file, a directory, a fifo file, or of unknown type;
`size( _Size_)`, with gives the size for a file, and
`mod_time( _Time_)`, which gives the last time a file was
modified according to some Operating System dependent
timestamp; `mode( _mode_)`, gives the permission flags for the
file, and `linkto( _FileName_)`, gives the file pointed to by a
symbolic link. Properties can be obtained through backtracking:
~~~~~
?- file_property('Makefile',P).
P = type(regular) ? ;
P = size(2375) ? ;
P = mod_time(990826911) ? ;
no
~~~~~
*/
/** @pred host_id(- _Id_)
Unify _Id_ with an identifier of the current host. YAP uses the
`hostid` function when available,
*/
/** @pred host_name(- _Name_)
Unify _Name_ with a name for the current host. YAP uses the
`hostname` function in Unix systems when available, and the
`GetComputerName` function in WIN32 systems.
*/
/** @pred make_directory(+ _Dir_)
Create a directory _Dir_. The name of the directory must be an atom.
*/
/** @pred mktemp( _Spec_,- _File_)
Direct interface to `mktemp`: given a _Spec_, that is a file
name with six _X_ to it, create a file name _File_. Use
tmpnam/1 instead.
*/
/** @pred mktime(+_Datime_, - _Seconds_)
The `mktime/2` procedure receives a term of the form _datime(+ _Year_,
+ _Month_, + _DayOfTheMonth_, + _Hour_, + _Minute_, + _Second_)_ and
returns the number of _Seconds_ elapsed since 00:00:00 on January 1,
1970, Coordinated Universal Time (UTC). The user provides information
on _Year_, _Month_, _DayOfTheMonth_, _Hour_, _Minute_, and
_Second_. The _Hour_ is given on local time. This function uses the
WIN32 `GetLocalTime` function or the Unix `mktime` function.
~~~~~
?- mktime(datime(2001,5,28,15,29,46),X).
X = 991081786 ? ;
~~~~~
*/
/** @pred pid(- _Id_)
Unify _Id_ with the process identifier for the current
process. An interface to the <tt>getpid</tt> function.
*/
/** @pred popen(+ _Command_, + _TYPE_, - _Stream_)
Interface to the <tt>popen</tt> function. It opens a process by creating a
pipe, forking and invoking _Command_ on the current shell. Since a
pipe is by definition unidirectional the _Type_ argument may be
`read` or `write`, not both. The stream should be closed
using close/1, there is no need for a special `pclose`
command.
The following example demonstrates the use of popen/3 to process
the output of a command, as exec/3 would do:
~~~~~{.prolog}
?- popen(ls,read,X),repeat, get0(X,C), (C = -1, ! ; put(C)).
X = 'C:\\cygwin\\home\\administrator' ?
~~~~~
The WIN32 implementation of popen/3 relies on exec/3.
*/
/** @pred rename_file(+ _OldFile_,+ _NewFile_)
Create file _OldFile_ to _NewFile_. This predicate uses the
`C` built-in function `rename`.
*/
/** @pred shell
Start a new shell and leave YAP in background until the shell
completes. YAP uses the shell given by the environment variable
`SHELL`. In WIN32 environment YAP will use `COMSPEC` if
`SHELL` is undefined.
*/
/** @pred shell(+ _Command_)
Execute command _Command_ under a new shell. YAP will be in
background until the command completes. In Unix environments YAP uses
the shell given by the environment variable `SHELL` with the option
`" -c "`. In WIN32 environment YAP will use `COMSPEC` if
`SHELL` is undefined, in this case with the option `" /c "`.
*/
/** @pred shell(+ _Command_,- _Status_)
Execute command _Command_ under a new shell and unify _Status_
with the exit for the command. YAP will be in background until the
command completes. In Unix environments YAP uses the shell given by the
environment variable `SHELL` with the option `" -c "`. In
WIN32 environment YAP will use `COMSPEC` if `SHELL` is
undefined, in this case with the option `" /c "`.
*/
/** @pred sleep(+ _Time_)
Block the current thread for _Time_ seconds. When YAP is compiled
without multi-threading support, this predicate blocks the YAP process.
The number of seconds must be a positive number, and it may an integer
or a float. The Unix implementation uses `usleep` if the number of
seconds is below one, and `sleep` if it is over a second. The WIN32
implementation uses `Sleep` for both cases.
*/
/** @pred system
Start a new default shell and leave YAP in background until the shell
completes. YAP uses `/bin/sh` in Unix systems and `COMSPEC` in
WIN32.
*/
/** @pred system(+ _Command_,- _Res_)
Interface to `system`: execute command _Command_ and unify
_Res_ with the result.
*/
/** @pred tmp_file(+_Base_, - _File_)
Create a name for a temporary file. _Base_ is an user provided
identifier for the category of file. The _TmpName_ is guaranteed to
be unique. If the system halts, it will automatically remove all created
temporary files.
*/
/** @pred tmpnam(- _File_)
Interface with _tmpnam_: obtain a new, unique file name _File_.
*/
/** @pred working_directory(- _Old_,+ _New_)
Unify _Old_ with an absolute path to the current working directory
and change working directory to _New_. Use the pattern
`working_directory(CWD, CWD)` to get the current directory. See
also `absolute_file_name/2` and chdir/1.
*/
:- module(operating_system_support, [
datime/1,
delete_file/1,

View File

@ -14,7 +14,120 @@
* comments: Term manipulation operations *
* *
*************************************************************************/
/** @defgroup Terms Utilities On Terms
@ingroup YAPLibrary
@{
The next routines provide a set of commonly used utilities to manipulate
terms. Most of these utilities have been implemented in `C` for
efficiency. They are available through the
`use_module(library(terms))` command.
@pred cyclic_term(? _Term_)
Succeed if the argument _Term_ is not a cyclic term.
*/
/** @pred term_subsumer(? _T1_, ? _T2_, ? _Subsumer_)
Succeed if _Subsumer_ unifies with the least general
generalization over _T1_ and
_T2_.
*/
/** @pred new_variables_in_term(+ _Variables_,? _Term_, - _OutputVariables_)
Unify _OutputVariables_ with all variables occurring in _Term_ that are not in the list _Variables_.
*/
/** @pred subsumes(? _Term1_, ? _Term2_)
Succeed if _Term1_ subsumes _Term2_. Variables in term
_Term1_ are bound so that the two terms become equal.
*/
/** @pred subsumes_chk(? _Term1_, ? _Term2_)
Succeed if _Term1_ subsumes _Term2_ but does not bind any
variable in _Term1_.
*/
/** @pred term_hash(+ _Term_, + _Depth_, + _Range_, ? _Hash_)
Unify _Hash_ with a positive integer calculated from the structure
of the term. The range of the positive integer is from `0` to, but
not including, _Range_. If _Depth_ is `-1` the whole term
is considered. Otherwise, the term is considered only up to depth
`1`, where the constants and the principal functor have depth
`1`, and an argument of a term with depth _I_ has depth _I+1_.
*/
/** @pred term_hash(+ _Term_, ? _Hash_)
If _Term_ is ground unify _Hash_ with a positive integer
calculated from the structure of the term. Otherwise the argument
_Hash_ is left unbound. The range of the positive integer is from
`0` to, but not including, `33554432`.
*/
/** @pred unifiable(? _Term1_, ? _Term2_, - _Bindings_)
Succeed if _Term1_ and _Term2_ are unifiable with substitution
_Bindings_.
*/
/** @pred variable_in_term(? _Term_,? _Var_)
Succeed if the second argument _Var_ is a variable and occurs in
term _Term_.
*/
/** @pred variables_within_term(+ _Variables_,? _Term_, - _OutputVariables_)
Unify _OutputVariables_ with the subset of the variables _Variables_ that occurs in _Term_.
*/
/** @pred variant(? _Term1_, ? _Term2_)
Succeed if _Term1_ and _Term2_ are variant terms.
*/
:- module(terms, [
term_hash/2,
term_hash/4,

View File

@ -19,6 +19,45 @@
time_out/3
]).
/** @defgroup Timeout Calls With Timeout
@ingroup YAPLibrary
@{
The <tt>time_out/3</tt> command relies on the <tt>alarm/3</tt> built-in to
implement a call with a maximum time of execution. The command is
available with the `use_module(library(timeout))` command.
@pred time_out(+ _Goal_, + _Timeout_, - _Result_)
Execute goal _Goal_ with time limited _Timeout_, where
_Timeout_ is measured in milliseconds. If the goal succeeds, unify
_Result_ with success. If the timer expires before the goal
terminates, unify _Result_ with <tt>time_out</tt>.
This command is implemented by activating an alarm at procedure
entry. If the timer expires before the goal completes, the alarm will
throw an exception _timeout_.
One should note that time_out/3 is not reentrant, that is, a goal
called from `time_out` should never itself call
time_out/3. Moreover, time_out/3 will deactivate any previous
alarms set by alarm/3 and vice-versa, hence only one of these
calls should be used in a program.
Last, even though the timer is set in milliseconds, the current
implementation relies on <tt>alarm/3</tt>, and therefore can only offer
precision on the scale of seconds.
*/
:- meta_predicate time_out(0,+,-).
:- use_module(library(hacks), [

View File

@ -23,6 +23,65 @@
to match the old tree and a pattern to match the new tree.
*/
/** @defgroup Trees Updatable Binary Trees
@ingroup YAPLibrary
@{
The following queue manipulation routines are available once
included with the `use_module(library(trees))` command.
@pred get_label(+ _Index_, + _Tree_, ? _Label_)
Treats the tree as an array of _N_ elements and returns the
_Index_-th.
*/
/** @pred list_to_tree(+ _List_, - _Tree_)
Takes a given _List_ of _N_ elements and constructs a binary
_Tree_.
*/
/** @pred map_tree(+ _Pred_, + _OldTree_, - _NewTree_)
Holds when _OldTree_ and _NewTree_ are binary trees of the same shape
and `Pred(Old,New)` is true for corresponding elements of the two trees.
*/
/** @pred put_label(+ _Index_, + _OldTree_, + _Label_, - _NewTree_)
constructs a new tree the same shape as the old which moreover has the
same elements except that the _Index_-th one is _Label_.
*/
/** @pred tree_size(+ _Tree_, - _Size_)
Calculates the number of elements in the _Tree_.
*/
/** @pred tree_to_list(+ _Tree_, - _List_)
Is the converse operation to list_to_tree.
*/
:- module(trees, [
get_label/3,
list_to_tree/2,

View File

@ -5,6 +5,148 @@
version: $ID$
****************************************/
/** @defgroup Tries Trie DataStructure
@ingroup YAPLibrary
@{
The next routines provide a set of utilities to create and manipulate
prefix trees of Prolog terms. Tries were originally proposed to
implement tabling in Logic Programming, but can be used for other
purposes. The tries will be stored in the Prolog database and can seen
as alternative to `assert` and `record` family of
primitives. Most of these utilities have been implemented in `C`
for efficiency. They are available through the
`use_module(library(tries))` command.
*/
/** @pred trie_check_entry(+ _Trie_,+ _Term_,- _Ref_)
Succeeds if a variant of term _Term_ is in trie _Trie_. An handle
_Ref_ gives a reference to the term.
*/
/** @pred trie_close(+ _Id_)
Close trie with identifier _Id_.
*/
/** @pred trie_close_all
Close all available tries.
*/
/** @pred trie_get_entry(+ _Ref_,- _Term_)
Unify _Term_ with the entry for handle _Ref_.
*/
/** @pred trie_load(+ _Trie_,+ _FileName_)
Load trie _Trie_ from the contents of file _FileName_.
*/
/** @pred trie_max_stats(- _Memory_,- _Tries_,- _Entries_,- _Nodes_)
Give maximal statistics on tries, including the amount of memory,
_Memory_, the number of tries, _Tries_, the number of entries,
_Entries_, and the total number of nodes, _Nodes_.
*/
/** @pred trie_mode(? _Mode_)
Unify _Mode_ with trie operation mode. Allowed values are either
`std` (default) or `rev`.
*/
/** @pred trie_open(- _Id_)
Open a new trie with identifier _Id_.
*/
/** @pred trie_print(+ _Trie_)
Print trie _Trie_ on standard output.
*/
/** @pred trie_put_entry(+ _Trie_,+ _Term_,- _Ref_)
Add term _Term_ to trie _Trie_. The handle _Ref_ gives
a reference to the term.
*/
/** @pred trie_remove_entry(+ _Ref_)
Remove entry for handle _Ref_.
*/
/** @pred trie_remove_subtree(+ _Ref_)
Remove subtree rooted at handle _Ref_.
*/
/** @pred trie_save(+ _Trie_,+ _FileName_)
Dump trie _Trie_ into file _FileName_.
*/
/** @pred trie_stats(- _Memory_,- _Tries_,- _Entries_,- _Nodes_)
Give generic statistics on tries, including the amount of memory,
_Memory_, the number of tries, _Tries_, the number of entries,
_Entries_, and the total number of nodes, _Nodes_.
*/
/** @pred trie_usage(+ _Trie_,- _Entries_,- _Nodes_,- _VirtualNodes_)
Give statistics on trie _Trie_, the number of entries,
_Entries_, and the total number of nodes, _Nodes_, and the
number of _VirtualNodes_.
*/
:- module(tries, [
trie_open/1,
trie_close/1,

View File

@ -8,6 +8,32 @@
% by Vitor Santos Costa.
%
/** @defgroup UGraphs Unweighted Graphs
@ingroup YAPLibrary
@{
The following graph manipulation routines are based in code originally
written by Richard O'Keefe. The code was then extended to be compatible
with the SICStus Prolog ugraphs library. The routines assume directed
graphs, undirected graphs may be implemented by using two edges. Graphs
are represented in one of two ways:
+ The P-representation of a graph is a list of (from-to) vertex
pairs, where the pairs can be in any old order. This form is
convenient for input/output.
The S-representation of a graph is a list of (vertex-neighbors)
pairs, where the pairs are in standard order (as produced by keysort)
and the neighbors of each vertex are also in standard order (as
produced by sort). This form is convenient for many calculations.
These built-ins are available once included with the
`use_module(library(ugraphs))` command.
*/
/* The P-representation of a graph is a list of (from-to) vertex
pairs, where the pairs can be in any old order. This form is
convenient for input/output.
@ -30,6 +56,243 @@
s_transpose transposes a graph in S-form, cost O(|V|^2).
*/
/** @pred vertices_edges_to_ugraph(+ _Vertices_, + _Edges_, - _Graph_)
Given a graph with a set of vertices _Vertices_ and a set of edges
_Edges_, _Graph_ must unify with the corresponding
s-representation. Note that the vertices without edges will appear in
_Vertices_ but not in _Edges_. Moreover, it is sufficient for a
vertex to appear in _Edges_.
~~~~~{.prolog}
?- vertices_edges_to_ugraph([],[1-3,2-4,4-5,1-5],L).
L = [1-[3,5],2-[4],3-[],4-[5],5-[]] ?
~~~~~
In this case all edges are defined implicitly. The next example shows
three unconnected edges:
~~~~~{.prolog}
?- vertices_edges_to_ugraph([6,7,8],[1-3,2-4,4-5,1-5],L).
L = [1-[3,5],2-[4],3-[],4-[5],5-[],6-[],7-[],8-[]] ?
~~~~~
*/
/** @pred add_edges(+ _Graph_, + _Edges_, - _NewGraph_)
Unify _NewGraph_ with a new graph obtained by adding the list of
edges _Edges_ to the graph _Graph_. In the next example:
~~~~~{.prolog}
?- add_edges([1-[3,5],2-[4],3-[],4-[5],5-[],6-[],
7-[],8-[]],[1-6,2-3,3-2,5-7,3-2,4-5],NL).
NL = [1-[3,5,6],2-[3,4],3-[2],4-[5],5-[7],6-[],7-[],8-[]]
~~~~~
*/
/** @pred add_vertices(+ _Graph_, + _Vertices_, - _NewGraph_)
Unify _NewGraph_ with a new graph obtained by adding the list of
vertices _Vertices_ to the graph _Graph_. In the next example:
~~~~~{.prolog}
?- add_vertices([1-[3,5],2-[4],3-[],4-[5],
5-[],6-[],7-[],8-[]],
[0,2,9,10,11],
NG).
NG = [0-[],1-[3,5],2-[4],3-[],4-[5],5-[],
6-[],7-[],8-[],9-[],10-[],11-[]]
~~~~~
*/
/** @pred complement(+ _Graph_, - _NewGraph_)
Unify _NewGraph_ with the graph complementary to _Graph_.
In the next example:
~~~~~{.prolog}
?- complement([1-[3,5],2-[4],3-[],
4-[1,2,7,5],5-[],6-[],7-[],8-[]], NL).
NL = [1-[2,4,6,7,8],2-[1,3,5,6,7,8],3-[1,2,4,5,6,7,8],
4-[3,5,6,8],5-[1,2,3,4,6,7,8],6-[1,2,3,4,5,7,8],
7-[1,2,3,4,5,6,8],8-[1,2,3,4,5,6,7]]
~~~~~
*/
/** @pred compose(+ _LeftGraph_, + _RightGraph_, - _NewGraph_)
Compose the graphs _LeftGraph_ and _RightGraph_ to form _NewGraph_.
In the next example:
~~~~~{.prolog}
?- compose([1-[2],2-[3]],[2-[4],3-[1,2,4]],L).
L = [1-[4],2-[1,2,4],3-[]]
~~~~~
*/
/** @pred del_edges(+ _Graph_, + _Edges_, - _NewGraph_)
Unify _NewGraph_ with a new graph obtained by removing the list of
edges _Edges_ from the graph _Graph_. Notice that no vertices
are deleted. In the next example:
~~~~~{.prolog}
?- del_edges([1-[3,5],2-[4],3-[],4-[5],5-[],
6-[],7-[],8-[]],
[1-6,2-3,3-2,5-7,3-2,4-5,1-3],NL).
NL = [1-[5],2-[4],3-[],4-[],5-[],6-[],7-[],8-[]]
~~~~~
*/
/** @pred del_vertices(+ _Graph_, + _Vertices_, - _NewGraph_)
Unify _NewGraph_ with a new graph obtained by deleting the list of
vertices _Vertices_ and all the edges that start from or go to a
vertex in _Vertices_ to the graph _Graph_. In the next example:
~~~~~{.prolog}
?- del_vertices([2,1],[1-[3,5],2-[4],3-[],
4-[5],5-[],6-[],7-[2,6],8-[]],NL).
NL = [3-[],4-[5],5-[],6-[],7-[6],8-[]]
~~~~~
*/
/** @pred edges(+ _Graph_, - _Edges_)
Unify _Edges_ with all edges appearing in graph
_Graph_. In the next example:
~~~~~{.prolog}
?- vertices([1-[3,5],2-[4],3-[],4-[5],5-[]], V).
L = [1,2,3,4,5]
~~~~~
*/
/** @pred neighbors(+ _Vertex_, + _Graph_, - _Vertices_)
Unify _Vertices_ with the list of neighbors of vertex _Vertex_
in _Graph_. If the vertice is not in the graph fail. In the next
example:
~~~~~{.prolog}
?- neighbors(4,[1-[3,5],2-[4],3-[],
4-[1,2,7,5],5-[],6-[],7-[],8-[]],
NL).
NL = [1,2,7,5]
~~~~~
*/
/** @pred neighbours(+ _Vertex_, + _Graph_, - _Vertices_)
Unify _Vertices_ with the list of neighbours of vertex _Vertex_
in _Graph_. In the next example:
~~~~~{.prolog}
?- neighbours(4,[1-[3,5],2-[4],3-[],
4-[1,2,7,5],5-[],6-[],7-[],8-[]], NL).
NL = [1,2,7,5]
~~~~~
*/
/** @pred reachable(+ _Node_, + _Graph_, - _Vertices_)
Unify _Vertices_ with the set of all vertices in graph
_Graph_ that are reachable from _Node_. In the next example:
~~~~~{.prolog}
?- reachable(1,[1-[3,5],2-[4],3-[],4-[5],5-[]],V).
V = [1,3,5]
~~~~~
*/
/** @pred top_sort(+ _Graph_, - _Sort0_, - _Sort_)
Generate the difference list _Sort_- _Sort0_ as a topological
sorting of graph _Graph_, if one is possible.
*/
/** @pred top_sort(+ _Graph_, - _Sort_)
Generate the set of nodes _Sort_ as a topological sorting of graph
_Graph_, if one is possible.
In the next example we show how topological sorting works for a linear graph:
~~~~~{.prolog}
?- top_sort([_138-[_219],_219-[_139], _139-[]],L).
L = [_138,_219,_139]
~~~~~
*/
/** @pred transitive_closure(+ _Graph_, + _Closure_)
Generate the graph _Closure_ as the transitive closure of graph
_Graph_.
In the next example:
~~~~~{.prolog}
?- transitive_closure([1-[2,3],2-[4,5],4-[6]],L).
L = [1-[2,3,4,5,6],2-[4,5,6],4-[6]]
~~~~~
*/
/** @pred vertices(+ _Graph_, - _Vertices_)
Unify _Vertices_ with all vertices appearing in graph
_Graph_. In the next example:
~~~~~{.prolog}
?- vertices([1-[3,5],2-[4],3-[],4-[5],5-[]], V).
L = [1,2,3,4,5]
~~~~~
*/
:- module(ugraphs,
[
add_vertices/3,

View File

@ -3,6 +3,7 @@
% Updated: 2006
% Purpose: Directed Graph Processing Utilities.
:- module( undgraphs,
[
undgraph_add_edge/4,
@ -18,6 +19,41 @@
undgraph_components/2,
undgraph_min_tree/2]).
/** @defgroup UnDGraphs Undirected Graphs
@ingroup YAPLibrary
@{
The following graph manipulation routines use the red-black tree graph
library to implement undirected graphs. Mostly, this is done by having
two directed edges per undirected edge.
@pred undgraph_new(+ _Graph_)
Create a new directed graph. This operation must be performed before
trying to use the graph.
*/
/** @pred undgraph_complement(+ _Graph_, - _NewGraph_)
Unify _NewGraph_ with the graph complementary to _Graph_.
*/
/** @pred undgraph_vertices(+ _Graph_, - _Vertices_)
Unify _Vertices_ with all vertices appearing in graph
_Graph_.
*/
:- reexport( library(dgraphs),
[
dgraph_new/1 as undgraph_new,
@ -66,6 +102,14 @@ undgraph_add_edge(Vs0,V1,V2,Vs2) :-
dgraphs:dgraph_new_edge(V1,V2,Vs0,Vs1),
dgraphs:dgraph_new_edge(V2,V1,Vs1,Vs2).
/** @pred undgraph_add_edges(+ _Graph_, + _Edges_, - _NewGraph_)
Unify _NewGraph_ with a new graph obtained by adding the list of
edges _Edges_ to the graph _Graph_.
*/
undgraph_add_edges(G0, Edges, GF) :-
dup_edges(Edges, DupEdges),
dgraph_add_edges(G0, DupEdges, GF).
@ -74,11 +118,27 @@ dup_edges([],[]).
dup_edges([E1-E2|Edges], [E1-E2,E2-E1|DupEdges]) :-
dup_edges(Edges, DupEdges).
/** @pred undgraph_add_vertices(+ _Graph_, + _Vertices_, - _NewGraph_)
Unify _NewGraph_ with a new graph obtained by adding the list of
vertices _Vertices_ to the graph _Graph_.
*/
undgraph_add_vertices(G, [], G).
undgraph_add_vertices(G0, [V|Vs], GF) :-
dgraph_add_vertex(G0, V, GI),
undgraph_add_vertices(GI, Vs, GF).
/** @pred undgraph_edges(+ _Graph_, - _Edges_)
Unify _Edges_ with all edges appearing in graph
_Graph_.
*/
undgraph_edges(Vs,Edges) :-
dgraph_edges(Vs,DupEdges),
remove_dups(DupEdges,Edges).
@ -90,6 +150,14 @@ remove_dups([V1-V2|DupEdges],NEdges) :- V1 @< V2, !,
remove_dups([_|DupEdges],Edges) :-
remove_dups(DupEdges,Edges).
/** @pred undgraph_neighbours(+ _Vertex_, + _Graph_, - _Vertices_)
Unify _Vertices_ with the list of neighbours of vertex _Vertex_
in _Graph_.
*/
undgraph_neighbours(V,Vertices,Children) :-
dgraph_neighbours(V,Vertices,Children0),
(
@ -113,6 +181,15 @@ undgraph_del_edge(Vs0,V1,V2,VsF) :-
dgraph_del_edge(Vs0,V1,V2,Vs1),
dgraph_del_edge(Vs1,V2,V1,VsF).
/** @pred undgraph_del_edges(+ _Graph_, + _Edges_, - _NewGraph_)
Unify _NewGraph_ with a new graph obtained by removing the list of
edges _Edges_ from the graph _Graph_. Notice that no vertices
are deleted.
*/
undgraph_del_edges(G0, Edges, GF) :-
dup_edges(Edges,DupEdges),
dgraph_del_edges(G0, DupEdges, GF).
@ -128,6 +205,15 @@ undgraph_del_vertex(Vs0, V, Vsf) :-
),
rb_partial_map(Vsi, RealBackEdges, del_edge(V), Vsf).
/** @pred undgraph_del_vertices(+ _Graph_, + _Vertices_, - _NewGraph_)
Unify _NewGraph_ with a new graph obtained by deleting the list of
vertices _Vertices_ and all the edges that start from or go to a
vertex in _Vertices_ to the graph _Graph_.
*/
undgraph_del_vertices(G0, Vs, GF) :-
sort(Vs,SortedVs),
delete_all(SortedVs, [], BackEdges, G0, GI),

View File

@ -228,7 +228,8 @@ c_ext( S, Mod, F ) :-
number_string(A, AS),
stream_property( S, position( Pos ) ),
stream_position_data( line_count, Pos, Line ),
assert( node( Mod, N/A, F-Line, Fu ) ),
Line0 is Line-1,
assert( node( Mod, N/A, F-Line0, Fu ) ),
handle_pred( Mod, N, A, F )
).
@ -1039,8 +1040,8 @@ c_links :-
clinks(S).
clinks(S) :-
node( M, P, _, c(F)),
format( S, ':- foreign_predicate( ~q , ~q ).~n', [M:P, F] ),
node( M, P, File-Line, c(F)),
format( S, ':- foreign_predicate( ~q , ~q, ~q, ~d ).~n', [M:P, F, File, Line] ),
fail.
clinks(S) :-
close(S).
@ -1436,13 +1437,16 @@ atom2([]) --> [].
add_comments :-
open( commands, write, S ),
findall(File, do_comment( File, Line, C, Type, Dup), Fs ),
findall(File, do_comment( File, Line, C, Type, Dup), Fs0 ),
(
sort(Fs0, Fs),
member( File, Fs ),
setof(Line-C-Type-Dup, do_comment( File, Line, C, Type, Dup) , Lines0 ),
reverse( Lines0, Lines),
member(Line-Comment-Type-Dup, Lines),
format(S, '# ~a~nawk \'NR==~d{print ~q}7\' ~a~n~n',[Dup,Line, Comment, File])
check_comment( Comment, CN, Line, File ),
Line1 is Line-1,
format(S, '#~a~ncat << "EOF" > tmp~n~sEOF~nsed -e "~dr tmp" ~a > x~n mv x ~a~n~n',[Dup,CN, Line1, File, File])
;
close(S)
),
@ -1450,6 +1454,33 @@ add_comments :-
add_comments :-
listing( open_comment ).
check_comment( Comment, CN, _Line, _File ) :-
string_codes( Comment, C),
check_quotes(0,C,[]),
( append(C0,[0'@,0'},0' ,0'*,0'/,10], C) ->
append(C0,[0'*,0'/,10], CN)
;
CN = C
),
!.
check_comment( Comment, Comment, Line, File ) :-
format(user_error,'*** bad comment ~a ~d~n~n~s~n~', [File,Line,Comment]).
check_quotes( 0 ) --> [].
check_quotes( 0 ) -->
"`", !,
check_quotes( 1 ).
check_quotes( 1 ) -->
"`", !,
check_quotes( 0 ).
check_quotes( 1 ) -->
"\"", !, { fail }.
check_quotes( 1 ) -->
"'", !, { fail }.
check_quotes( N ) -->
[_],
check_quotes( N ).
%%%
% ops_default sets operators back to YAP default.

View File

@ -438,6 +438,104 @@ error:
static
PRED_IMPL("char_type", 2, char_type, PL_FA_NONDETERMINISTIC)
/** @pred char_type(? _Char_, ? _Type_)
Tests or generates alternative _Types_ or _Chars_. The
character-types are inspired by the standard `C`
`<ctype.h>` primitives.
+ `alnum`
_Char_ is a letter (upper- or lowercase) or digit.
+ `alpha`
_Char_ is a letter (upper- or lowercase).
+ `csym`
_Char_ is a letter (upper- or lowercase), digit or the underscore (_). These are valid C- and Prolog symbol characters.
+ `csymf`
_Char_ is a letter (upper- or lowercase) or the underscore (_). These are valid first characters for C- and Prolog symbols
+ `ascii`
_Char_ is a 7-bits ASCII character (0..127).
+ `white`
_Char_ is a space or tab. E.i. white space inside a line.
+ `cntrl`
_Char_ is an ASCII control-character (0..31).
+ `digit`
_Char_ is a digit.
+ `digit( _Weight_)`
_Char_ is a digit with value _Weight_. I.e. `char_type(X, digit(6))` yields X = aaasaá'6'. Useful for parsing numbers.
+ `xdigit( _Weight_)`
_Char_ is a hexa-decimal digit with value _Weight_. I.e. char_type(a, xdigit(X) yields X = '10'. Useful for parsing numbers.
+ `graph`
_Char_ produces a visible mark on a page when printed. Note that the space is not included!
+ `lower`
_Char_ is a lower-case letter.
+ `lower(Upper)`
_Char_ is a lower-case version of _Upper_. Only true if _Char_ is lowercase and _Upper_ uppercase.
+ `to_lower(Upper)`
_Char_ is a lower-case version of Upper. For non-letters, or letter without case, _Char_ and Lower are the same. See also upcase_atom/2 and downcase_atom/2.
+ `upper`
_Char_ is an upper-case letter.
+ `upper(Lower)`
_Char_ is an upper-case version of Lower. Only true if _Char_ is uppercase and Lower lowercase.
+ `to_upper(Lower)`
_Char_ is an upper-case version of Lower. For non-letters, or letter without case, _Char_ and Lower are the same. See also upcase_atom/2 and downcase_atom/2.
+ `punct`
_Char_ is a punctuation character. This is a graph character that is not a letter or digit.
+ `space`
_Char_ is some form of layout character (tab, vertical-tab, newline, etc.).
+ `end_of_file`
_Char_ is -1.
+ `end_of_line`
_Char_ ends a line (ASCII: 10..13).
+ `newline`
_Char_ is a the newline character (10).
+ `period`
_Char_ counts as the end of a sentence (.,!,?).
+ `quote`
_Char_ is a quote-character.
+ `paren(Close)`
_Char_ is an open-parenthesis and Close is the corresponding close-parenthesis.
+ `code_type(? _Code_, ? _Type_)`
As char_type/2, but uses character-codes rather than
one-character atoms. Please note that both predicates are as
flexible as possible. They handle either representation if the
argument is instantiated and only will instantiate with an integer
code or one-character atom depending of the version used. See also
the prolog-flag double_quotes and the built-in predicates
atom_chars/2 and atom_codes/2.
*/
{ return do_char_type(A1, A2, PL__ctx, PL_CHAR);
}

730
os/pl-file.c Executable file → Normal file

File diff suppressed because it is too large Load Diff

28
os/pl-files.c Executable file → Normal file
View File

@ -836,6 +836,12 @@ PRED_IMPL("size_file", 2, size_file, 0)
static
PRED_IMPL("access_file", 2, access_file, 0)
/** @pred access_file(+ _F_,+ _M_)
Is the file accessible?
*/
{ PRED_LD
char *n;
int md;
@ -950,6 +956,13 @@ PRED_IMPL("same_file", 2, same_file, 0)
}
/** @pred file_base_name(+ _Name_,- _FileName_)
Give the path a full path _FullPath_ extract the _FileName_.
*/
static
PRED_IMPL("file_base_name", 2, file_base_name, 0)
{ char *n;
@ -993,7 +1006,6 @@ PRED_IMPL("tmp_file", 2, tmp_file, 0)
/** tmp_file_stream(+Mode, -File, -Stream)
*/
static
PRED_IMPL("tmp_file_stream", 3, tmp_file_stream, 0)
{ PRED_LD
@ -1201,6 +1213,20 @@ name_too_long(void)
}
/** @pred file_name_extension(? _Base_,? _Extension_, ? _Name_)
This predicate is used to add, remove or test filename extensions. The
main reason for its introduction is to deal with different filename
properties in a portable manner. If the file system is
case-insensitive, testing for an extension will be done
case-insensitive too. _Extension_ may be specified with or
without a leading dot (.). If an _Extension_ is generated, it
will not have a leading dot.
*/
static
PRED_IMPL("file_name_extension", 3, file_name_extension, 0)
{ PRED_LD

View File

@ -1369,6 +1369,13 @@ return rval;
static
PRED_IMPL("read_term", 3, read_term, PL_FA_ISO)
/** @pred read_term(+ _S_,- _T_,+ _Options_) is iso
Reads term _T_ from stream _S_ with execution controlled by the
same options as read_term/2.
*/
{ PRED_LD
IOSTREAM *s;
@ -1390,6 +1397,40 @@ return FALSE;
static
PRED_IMPL("read_term", 2, read_term, PL_FA_ISO)
/** @pred read_term(- _T_,+ _Options_) is iso
Reads term _T_ from the current input stream with execution
controlled by the following options:
+ term_position(- _Position_)
Unify _Position_ with a term describing the position of the stream
at the start of parse. Use stream_position_data/3 to obtain extra
information.
+ singletons(- _Names_)
Unify _Names_ with a list of the form _Name=Var_, where
_Name_ is the name of a non-anonymous singleton variable in the
original term, and `Var` is the variable's representation in
YAP.
The variables occur in left-to-right traversal order.
+ syntax_errors(+ _Val_)
Control action to be taken after syntax errors. See yap_flag/2
for detailed information.
+ variables(- _Names_)
Unify _Names_ with a list of the form _Name=Var_, where _Name_ is
the name of a non-anonymous variable in the original term, and _Var_
is the variable's representation in YAP.
The variables occur in left-to-right traversal order.
*/
{ PRED_LD
IOSTREAM *s;
@ -1498,6 +1539,13 @@ return Yap_GetFromSlot( tt PASS_REGS);
static
PRED_IMPL("atom_to_term", 3, atom_to_term, 0)
/** @pred atom_to_term(+ _Atom_, - _Term_, - _Bindings_)
Use _Atom_ as input to read_term/2 using the option `variable_names` and return the read term in _Term_ and the variable bindings in _Bindings_. _Bindings_ is a list of `Name = Var` couples, thus providing access to the actual variable names. See also read_term/2. If Atom has no valid syntax, a syntax_error exception is raised.
*/
{ return atom_to_term(A1, A2, A3);
}

View File

@ -1,3 +1,17 @@
/** @defgroup BDDs Binary Decision Diagrams and Friends
@ingroup YAPPackages
@{
This library provides an interface to the BDD package CUDD. It requires
CUDD compiled as a dynamic library. In Linux this is available out of
box in Fedora, but can easily be ported to other Linux
distributions. CUDD is available in the ports OSX package, and in
cygwin. To use it, call `:-use_module(library(bdd))`.
The following predicates construct a BDD:
*/
:- module(bdd, [
bdd_new/2,
@ -30,6 +44,21 @@ tell_warning :-
% create a new BDD from a tree.
/** @defgroup BDDs Binary Decision Diagrams and Friends
@ingroup YAPPackages
@{
This library provides an interface to the BDD package CUDD. It requires
CUDD compiled as a dynamic library. In Linux this is available out of
box in Fedora, but can easily be ported to other Linux
distributions. CUDD is available in the ports OSX package, and in
cygwin. To use it, call `:-use_module(library(bdd))`.
The following predicates construct a BDD:
*/
bdd_new(T, Bdd) :-
term_variables(T, Vars),
bdd_new(T, Vars, Bdd).
@ -39,6 +68,14 @@ bdd_new(T, Vars, cudd(M,X,VS,TrueVars)) :-
VS =.. [vs|TrueVars],
findall(Manager-Cudd, set_bdd(T, VS, Manager, Cudd), [M-X]).
/** @pred bdd_from_list(? _List_, ?_Vars_, - _BddHandle_)
Convert a _List_ of logical expressions of the form above, that
includes the set of free variables _Vars_, into a BDD accessible
through _BddHandle_.
*/
% create a new BDD from a list.
bdd_from_list(List, Vars, cudd(M,X,VS,TrueVars)) :-
term_variables(Vars, TrueVars),
@ -119,6 +156,27 @@ list_to_cudd([(V=Tree)|T], Manager, _Cudd0, CuddF) :-
V = cudd(Cudd),
list_to_cudd(T, Manager, Cudd, CuddF).
/** @pred mtbdd_new(? _Exp_, - _BddHandle_)
create a new algebraic decision diagram (ADD) from the logical
expression _Exp_. The expression may include:
+ Logical Variables:
a leaf-node can be a logical variable, or <em>parameter</em>.
+ Number
a leaf-node can also be any number
+ _X_ \* _Y_
product
+ _X_ + _Y_
sum
+ _X_ - _Y_
subtraction
+ or( _X_, _Y_), _X_ \/ _Y_
logical or
*/
mtbdd_new(T, Mtbdd) :-
term_variables(T, Vars),
mtbdd_new(T, Vars, Mtbdd).
@ -128,6 +186,39 @@ mtbdd_new(T, Vars, add(M,X,VS,Vars)) :-
functor(VS,vs,Sz),
findall(Manager-Cudd, (numbervars(VS,0,_),term_to_add(T,Sz,Manager,Cudd)), [M-X]).
/** @pred bdd_eval(+ _BDDHandle_, _Val_)
Unify _Val_ with the value of the logical expression compiled in
_BDDHandle_ given an assignment to its variables.
~~~~~
bdd_new(X+(Y+X)*(-Z), BDD),
[X,Y,Z] = [0,0,0],
bdd_eval(BDD, V),
writeln(V).
~~~~~
would write 0 in the standard output stream.
The Prolog code equivalent to <tt>bdd_eval/2</tt> is:
~~~~~
Tree = bdd(1, T, _Vs),
reverse(T, RT),
foldl(eval_bdd, RT, _, V).
eval_bdd(pp(P,X,L,R), _, P) :-
P is ( X/\L ) \/ ( (1-X) /\ R ).
eval_bdd(pn(P,X,L,R), _, P) :-
P is ( X/\L ) \/ ( (1-X) /\ (1-R) ).
~~~~~
First, the nodes are reversed to implement bottom-up evaluation. Then,
we use the `foldl` list manipulation predicate to walk every node,
computing the disjunction of the two cases and binding the output
variable. The top node gives the full expression value. Notice that
`(1- _X_)` implements negation.
*/
bdd_eval(cudd(M, X, Vars, _), Val) :-
cudd_eval(M, X, Vars, Val).
bdd_eval(add(M, X, Vars, _), Val) :-
@ -137,27 +228,102 @@ mtbdd_eval(add(M,X, Vars, _), Val) :-
add_eval(M, X, Vars, Val).
% get the BDD as a Prolog list from the CUDD C object
/** @pred bdd_tree(+ _BDDHandle_, _Term_)
Convert the BDD or ADD represented by _BDDHandle_ to a Prolog term
of the form `bdd( _Dir_, _Nodes_, _Vars_)` or `mtbdd( _Nodes_, _Vars_)`, respectively. The arguments are:
+
_Dir_ direction of the BDD, usually 1
+
_Nodes_ list of nodes in the BDD or ADD.
In a BDD nodes may be <tt>pp</tt> (both terminals are positive) or <tt>pn</tt>
(right-hand-side is negative), and have four arguments: a logical
variable that will be bound to the value of the node, the logical
variable corresponding to the node, a logical variable, a 0 or a 1 with
the value of the left-hand side, and a logical variable, a 0 or a 1
with the right-hand side.
+
_Vars_ are the free variables in the original BDD, or the parameters of the BDD/ADD.
As an example, the BDD for the expression `X+(Y+X)\*(-Z)` becomes:
~~~~~
bdd(1,[pn(N2,X,1,N1),pp(N1,Y,N0,1),pn(N0,Z,1,1)],vs(X,Y,Z))
~~~~~
*/
bdd_tree(cudd(M, X, Vars, _Vs), bdd(Dir, List, Vars)) :-
cudd_to_term(M, X, Vars, Dir, List).
bdd_tree(add(M, X, Vars, _), mtbdd(Tree, Vars)) :-
add_to_term(M, X, Vars, Tree).
/** @pred bdd_to_probability_sum_product(+ _BDDHandle_, - _Prob_)
Each node in a BDD is given a probability _Pi_. The total
probability of a corresponding sum-product network is _Prob_.
*/
bdd_to_probability_sum_product(cudd(M,X,_,Probs), Prob) :-
cudd_to_probability_sum_product(M, X, Probs, Prob).
/** @pred bdd_to_probability_sum_product(+ _BDDHandle_, - _Probs_, - _Prob_)
Each node in a BDD is given a probability _Pi_. The total
probability of a corresponding sum-product network is _Prob_, and
the probabilities of the inner nodes are _Probs_.
In Prolog, this predicate would correspond to computing the value of a
BDD. The input variables will be bound to probabilities, eg
`[ _X_, _Y_, _Z_] = [0.3.0.7,0.1]`, and the previous
`eval_bdd` would operate over real numbers:
~~~~~
Tree = bdd(1, T, _Vs),
reverse(T, RT),
foldl(eval_prob, RT, _, V).
eval_prob(pp(P,X,L,R), _, P) :-
P is X * L + (1-X) * R.
eval_prob(pn(P,X,L,R), _, P) :-
P is X * L + (1-X) * (1-R).
~~~~~
*/
bdd_to_probability_sum_product(cudd(M,X,_,_Probs), Probs, Prob) :-
cudd_to_probability_sum_product(M, X, Probs, Prob).
/** @pred bdd_close( _BDDHandle_)
close the BDD and release any resources it holds.
*/
bdd_close(cudd(M,_,_Vars, _)) :-
cudd_die(M).
bdd_close(add(M,_,_Vars, _)) :-
cudd_die(M).
/** @pred bdd_size(+ _BDDHandle_, - _Size_)
Unify _Size_ with the number of nodes in _BDDHandle_.
*/
bdd_size(cudd(M,Top,_Vars, _), Sz) :-
cudd_size(M,Top,Sz).
bdd_size(add(M,Top,_Vars, _), Sz) :-
cudd_size(M,Top,Sz).
/** @pred bdd_print(+ _BDDHandle_, + _File_)
Output bdd _BDDHandle_ as a dot file to _File_.
*/
bdd_print(cudd(M,Top,_Vars, _), File) :-
cudd_print(M, Top, File).
bdd_print(add(M,Top,_Vars, _), File) :-

View File

@ -1,3 +1,32 @@
/**
@defgroup Gecode_and_ClPbBFDbC Programming Finite Domain Constraints in YAP/Gecode
@ingroup Gecode
@{
The gecode/clp(fd) interface is designed to use the GECODE functionality
in a more CLP like style. It requires
~~~~~{.prolog}
:- use_module(library(gecode/clpfd)).
~~~~~
Several example programs are available with the distribution.
Integer variables are declared as:
+ _V_ in _A_.. _B_
declares an integer variable _V_ with range _A_ to _B_.
+ _Vs_ ins _A_.. _B_
declares a set of integer variabless _Vs_ with range _A_ to _B_.
+ boolvar( _V_)
declares a boolean variable.
+ boolvars( _Vs_)
declares a set of boolean variable.
Constraints supported are:
*/
:- module(gecode_clpfd, [
op(100, yf, []),
op(760, yfx, #<==>),
@ -199,22 +228,43 @@ process_constraints(B, B, _Env).
get_home(Env),
check(A, NA),
post( rel(NA, (#=)), Env, _).
/** @pred _X_ #= is det
all elements of _X_ must take the same value
*/
( A #\= ) :-
get_home(Env),
check(A, NA),
post( rel(NA, (#\=)), Env, _).
/** @pred _X_ #< is det
elements of _X_ must be decreasing or equal
*/
( A #< ) :-
get_home(Env),
check(A, NA),
post( rel(NA, (#<)), Env, _).
/** @pred _X_ #> is det
elements of _X_ must be increasing
*/
( A #> ) :-
get_home(Env),
check(A, NA),
post( rel(NA, (#>)), Env, _).
/** @pred _X_ #=< is det
elements of _X_ must be decreasing
*/
( A #=< ) :-
get_home(Env),
check(A, NA),
post( rel(NA, (#=<) ), Env, _).
/** @pred _X_ #>= is det
elements of _X_ must be increasinga or equal
*/
( A #>= ) :-
get_home(Env),
check(A, NA),
@ -1147,3 +1197,6 @@ l(NV, OV, A, B, [_|Vs]) :-
is_one(1).
/**
@}
*/

View File

@ -16,9 +16,258 @@
%% along with this program. If not, see <http://www.gnu.org/licenses/>.
%%=============================================================================
/** @defgroup Gecode Gecode Interface
@ingroup YAPPackages
@{
The gecode library intreface was designed and implemented by Denis
Duchier, with recent work by Vítor Santos Costa to port it to version 4
of gecode and to have an higher level interface,
@defgroup The_Gecode_Interface The Gecode Interface
@ingroup Gecode
@{
This text is due to Denys Duchier. The gecode interface requires
~~~~~{.prolog}
:- use_module(library(gecode)).
~~~~~
Several example programs are available with the distribution.
+ CREATING A SPACE
A space is gecodes data representation for a store of constraints:
~~~~~{.prolog}
Space := space
~~~~~
+ CREATING VARIABLES
Unlike in Gecode, variable objects are not bound to a specific Space. Each one
actually contains an index with which it is possible to access a Space-bound
Gecode variable. Variables can be created using the following expressions:
~~~~~{.prolog}
IVar := intvar(Space,SPEC...)
BVar := boolvar(Space)
SVar := setvar(Space,SPEC...)
~~~~~
where SPEC... is the same as in Gecode. For creating lists of variables use
the following variants:
~~~~~{.prolog}
IVars := intvars(Space,N,SPEC...)
BVars := boolvars(Space,N,SPEC...)
SVars := setvars(Space,N,SPEC...)
~~~~~
where N is the number of variables to create (just like for XXXVarArray in
Gecode). Sometimes an IntSet is necessary:
~~~~~{.prolog}
ISet := intset([SPEC...])
~~~~~
where each SPEC is either an integer or a pair (I,J) of integers. An IntSet
describes a set of ints by providing either intervals, or integers (which stand
for an interval of themselves). It might be tempting to simply represent an
IntSet as a list of specs, but this would be ambiguous with IntArgs which,
here, are represented as lists of ints.
~~~~~{.prolog}
Space += keep(Var)
Space += keep(Vars)
~~~~~
Variables can be marked as "kept". In this case, only such variables will be
explicitly copied during search. This could bring substantial benefits in
memory usage. Of course, in a solution, you can then only look at variables
that have been "kept". If no variable is marked as "kept", then they are all
kept. Thus marking variables as "kept" is purely an optimization.
+ CONSTRAINTS AND BRANCHINGS
all constraint and branching posting functions are available just like in
Gecode. Wherever a XXXArgs or YYYSharedArray is expected, simply use a list.
At present, there is no support for minimodel-like constraint posting.
Constraints and branchings are added to a space using:
~~~~~{.prolog}
Space += CONSTRAINT
Space += BRANCHING
~~~~~
For example:
~~~~~{.prolog}
Space += rel(X,'IRT_EQ',Y)
~~~~~
arrays of variables are represented by lists of variables, and constants are
represented by atoms with the same name as the Gecode constant
(e.g. 'INT_VAR_SIZE_MIN').
+ SEARCHING FOR SOLUTIONS
~~~~~{.prolog}
SolSpace := search(Space)
~~~~~
This is a backtrackable predicate that enumerates all solution spaces
(SolSpace). It may also take options:
~~~~~{.prolog}
SolSpace := search(Space,Options)
~~~~~
Options is a list whose elements maybe:
+ restart
to select the Restart search engine
+ threads=N
to activate the parallel search engine and control the number of
workers (see Gecode doc)
+ c_d=N
to set the commit distance for recomputation
+ a_d=N
to set the adaptive distance for recomputation
+ EXTRACTING INFO FROM A SOLUTION
An advantage of non Space-bound variables, is that you can use them both to
post constraints in the original space AND to consult their values in
solutions. Below are methods for looking up information about variables. Each
of these methods can either take a variable as argument, or a list of
variables, and returns resp. either a value, or a list of values:
~~~~~{.prolog}
Val := assigned(Space,X)
Val := min(Space,X)
Val := max(Space,X)
Val := med(Space,X)
Val := val(Space,X)
Val := size(Space,X)
Val := width(Space,X)
Val := regret_min(Space,X)
Val := regret_max(Space,X)
Val := glbSize(Space,V)
Val := lubSize(Space,V)
Val := unknownSize(Space,V)
Val := cardMin(Space,V)
Val := cardMax(Space,V)
Val := lubMin(Space,V)
Val := lubMax(Space,V)
Val := glbMin(Space,V)
Val := glbMax(Space,V)
Val := glb_ranges(Space,V)
Val := lub_ranges(Space,V)
Val := unknown_ranges(Space,V)
Val := glb_values(Space,V)
Val := lub_values(Space,V)
Val := unknown_values(Space,V)
~~~~~
+ DISJUNCTORS
Disjunctors provide support for disjunctions of clauses, where each clause is a
conjunction of constraints:
~~~~~{.prolog}
C1 or C2 or ... or Cn
~~~~~
Each clause is executed "speculatively": this means it does not affect the main
space. When a clause becomes failed, it is discarded. When only one clause
remains, it is committed: this means that it now affects the main space.
Example:
Consider the problem where either X=Y=0 or X=Y+(1 or 2) for variable X and Y
that take values in 0..3.
~~~~~{.prolog}
Space := space,
[X,Y] := intvars(Space,2,0,3),
~~~~~
First, we must create a disjunctor as a manager for our 2 clauses:
~~~~~{.prolog}
Disj := disjunctor(Space),
~~~~~
We can now create our first clause:
~~~~~{.prolog}
C1 := clause(Disj),
~~~~~
This clause wants to constrain X and Y to 0. However, since it must be
executed "speculatively", it must operate on new variables X1 and Y1 that
shadow X and Y:
~~~~~{.prolog}
[X1,Y1] := intvars(C1,2,0,3),
C1 += forward([X,Y],[X1,Y1]),
~~~~~
The forward(...) stipulation indicates which global variable is shadowed by
which clause-local variable. Now we can post the speculative clause-local
constraints for X=Y=0:
~~~~~{.prolog}
C1 += rel(X1,'IRT_EQ',0),
C1 += rel(Y1,'IRT_EQ',0),
~~~~~
We now create the second clause which uses X2 and Y2 to shadow X and Y:
~~~~~{.prolog}
C2 := clause(Disj),
[X2,Y2] := intvars(C2,2,0,3),
C2 += forward([X,Y],[X2,Y2]),
~~~~~
However, this clause also needs a clause-local variable Z2 taking values 1 or
2 in order to post the clause-local constraint X2=Y2+Z2:
~~~~~{.prolog}
Z2 := intvar(C2,1,2),
C2 += linear([-1,1,1],[X2,Y2,Z2],'IRT_EQ',0),
~~~~~
Finally, we can branch and search:
~~~~~{.prolog}
Space += branch([X,Y],'INT_VAR_SIZE_MIN','INT_VAL_MIN'),
SolSpace := search(Space),
~~~~~
and lookup values of variables in each solution:
~~~~~{.prolog}
[X_,Y_] := val(SolSpace,[X,Y]).
~~~~~
*/
:- module(gecode, [(:=)/2, op(500, xfx, ':='),
(+=)/2, op(500, xfx, '+=')]).
:- use_module(library(debug)).
:- op(500, xfx, ':=').

View File

@ -15,9 +15,97 @@
* *
*************************************************************************/
#if defined MYDDAS_MYSQL || defined MYDDAS_ODBC
:- load_foreign_files([myddas], [], init_myddas).
/* Initialize MYDDAS GLOBAL STRUCTURES */
:- c_db_initialize_myddas.
#ifdef DEBUG
:- yap_flag(single_var_warnings,on).
#endif
:- module(myddas,[
db_open/5,
db_open/4,
db_close/1,
db_close/0,
db_verbose/1,
db_module/1,
db_is_database_predicate/3,
#ifdef MYDDAS_STATS
db_stats/1,
db_stats/2,
db_stats_time/2,
#endif
db_sql/2,
db_sql/3,
db_sql_select/3,
db_prolog_select/2,
db_prolog_select/3,
db_prolog_select_multi/3,
db_command/2,
db_assert/2,
db_assert/1,
db_create_table/3,
db_export_view/4,
db_update/2,
db_get_attributes_types/2,
db_get_attributes_types/3,
db_number_of_fields/2,
db_number_of_fields/3,
db_multi_queries_number/2,
% myddas_top_level.ypp
#ifdef MYDDAS_TOP_LEVEL
db_top_level/4,
db_top_level/5,
db_datalog_select/3,
#endif
% myddas_assert_predicates.ypp
db_import/2,
db_import/3,
db_view/2,
db_view/3,
db_insert/2,
db_insert/3,
db_abolish/2,
db_listing/0,
db_listing/1
#ifdef MYDDAS_MYSQL
% myddas_mysql.ypp
,
db_my_result_set/1,
db_datalog_describe/1,
db_datalog_describe/2,
db_describe/3,
db_describe/2,
db_datalog_show_tables/1,
db_datalog_show_tables/0,
db_show_tables/2,
db_show_tables/1,
db_show_database/2,
db_show_databases/2,
db_show_databases/1,
db_change_database/2,
db_call_procedure/4,
db_call_procedure/3,
db_my_sql_mode/1,
db_my_sql_mode/2,
db_sql_mode/1,
db_sql_mode/2
#endif
]).
/**
@section MYDDAS MYDDAS
@defgroup MYDDAS The MYDDAS Data-base interface.
@ingroup YAPPackages
The MYDDAS database project was developed within a FCT project aiming at
the development of a highly efficient deductive database system, based
@ -713,92 +801,6 @@ You can see the available SQL Modes at the MySQL homepage at
*/
#if defined MYDDAS_MYSQL || defined MYDDAS_ODBC
:- load_foreign_files([myddas], [], init_myddas).
/* Initialize MYDDAS GLOBAL STRUCTURES */
:- c_db_initialize_myddas.
#ifdef DEBUG
:- yap_flag(single_var_warnings,on).
#endif
:- module(myddas,[
db_open/5,
db_open/4,
db_close/1,
db_close/0,
db_verbose/1,
db_module/1,
db_is_database_predicate/3,
#ifdef MYDDAS_STATS
db_stats/1,
db_stats/2,
db_stats_time/2,
#endif
db_sql/2,
db_sql/3,
db_sql_select/3,
db_prolog_select/2,
db_prolog_select/3,
db_prolog_select_multi/3,
db_command/2,
db_assert/2,
db_assert/1,
db_create_table/3,
db_export_view/4,
db_update/2,
db_get_attributes_types/2,
db_get_attributes_types/3,
db_number_of_fields/2,
db_number_of_fields/3,
db_multi_queries_number/2,
% myddas_top_level.ypp
#ifdef MYDDAS_TOP_LEVEL
db_top_level/4,
db_top_level/5,
db_datalog_select/3,
#endif
% myddas_assert_predicates.ypp
db_import/2,
db_import/3,
db_view/2,
db_view/3,
db_insert/2,
db_insert/3,
db_abolish/2,
db_listing/0,
db_listing/1
#ifdef MYDDAS_MYSQL
% myddas_mysql.ypp
,
db_my_result_set/1,
db_datalog_describe/1,
db_datalog_describe/2,
db_describe/3,
db_describe/2,
db_datalog_show_tables/1,
db_datalog_show_tables/0,
db_show_tables/2,
db_show_tables/1,
db_show_database/2,
db_show_databases/2,
db_show_databases/1,
db_change_database/2,
db_call_procedure/4,
db_call_procedure/3,
db_my_sql_mode/1,
db_my_sql_mode/2,
db_sql_mode/1,
db_sql_mode/2
#endif
]).
#ifdef MYDDAS_TOP_LEVEL
:- use_module(myddas_top_level,[
db_top_level/4,

View File

@ -26,9 +26,29 @@
/* atom_codes/2, number_codes/2 and throw/1 are ISO predicates, mapped to
* the Quintus equivalent here.
*/
/** @pred atom_codes(? _A_,? _L_) is iso
The predicate holds when at least one of the arguments is ground
(otherwise, an error message will be displayed). The argument _A_ will
be unified with an atom and _L_ with the list of the ASCII
codes for the characters of the external representation of _A_.
*/
atom_codes( Atom, Codes ) :-
atom_chars( Atom, Codes ).
/** @pred number_codes(? _A_,? _L_) is iso
The predicate holds when at least one of the arguments is ground
(otherwise, an error message will be displayed). The argument _A_
will be unified with a number and _L_ with the list of the ASCII
codes for the characters of the external representation of _A_.
*/
number_codes( Number, Codes ) :-
number_chars( Number, Codes ).
@ -53,6 +73,14 @@ select( Element, [H|T0], [H|T1] ):-
/* is_list( +List ) holds when List is a list.
*/
/** @pred is_list(+ _List_)
True when _List_ is a proper list. That is, _List_
is bound to the empty list (nil) or a term with functor '.' and arity 2.
*/
is_list( List ) :-
nonvar( List ),
is_list1( List ).

View File

@ -10,7 +10,7 @@
/** @defgroup YAPAbsoluteFileName File Name Resolution
@ingroup YAPProgramming
@ingroup YAPBuiltins
Support for file name resolution through absolute_file_name/3 and
friends. These utility built-ins describe a list of directories that

View File

@ -15,11 +15,26 @@
* *
*************************************************************************/
/**
@addtogroup YAPArrays
*/
%
% These are the array built-in predicates. They will only work if
% YAP_ARRAYS is defined in Yap.h.m4.
%
/** @pred array(+ _Name_, + _Size_)
Creates a new dynamic array. The _Size_ must evaluate to an
integer. The _Name_ may be either an atom (named array) or an
unbound variable (anonymous array).
Dynamic arrays work as standard compound terms, hence space for the
array is recovered automatically on backtracking.
*/
array(Obj, Size) :-
'$create_array'(Obj, Size).
@ -65,6 +80,18 @@ array(Obj, Size) :-
'$add_array_entries'(Tail, G, NG).
/** @pred static_array_properties(? _Name_, ? _Size_, ? _Type_)
Show the properties size and type of a static array with name
_Name_. Can also be used to enumerate all current
static arrays.
This built-in will silently fail if the there is no static array with
that name.
*/
static_array_properties(Name, Size, Type) :-
atom(Name), !,
'$static_array_properties'(Name, Size, Type).

View File

@ -18,10 +18,19 @@
:- use_system_module( '$_errors', ['$do_error'/2]).
/**
* @short: Atom, and Atomic manipulation predicates in YAP
* @addtogroup Predicates_on_Atoms
*
*/
/** @pred atom_concat(+ _As_,? _A_)
The predicate holds when the first argument is a list of atoms, and the
second unifies with the atom obtained by concatenating all the atoms in
the first list.
*/
atom_concat(Xs,At) :-
( var(At) ->
'$atom_concat'(Xs, At )
@ -62,9 +71,42 @@ atom_concat(Xs,At) :-
'$process_atom_holes'(Unbound).
/** @pred atomic_list_concat(+ _As_,? _A_)
The predicate holds when the first argument is a list of atomic terms, and
the second unifies with the atom obtained by concatenating all the
atomic terms in the first list. The first argument thus may contain
atoms or numbers.
*/
atomic_list_concat(L,At) :-
atomic_concat(L, At).
/** @pred atomic_list_concat(? _As_,+ _Separator_,? _A_)
Creates an atom just like atomic_list_concat/2, but inserts
_Separator_ between each pair of atoms. For example:
~~~~~{.prolog}
?- atomic_list_concat([gnu, gnat], `, `, A).
A = `gnu, gnat`
~~~~~
YAP emulates the SWI-Prolog version of this predicate that can also be
used to split atoms by instantiating _Separator_ and _Atom_ as
shown below.
~~~~~{.prolog}
?- atomic_list_concat(L, -, 'gnu-gnat').
L = [gnu, gnat]
~~~~~
*/
atomic_list_concat(L, El, At) :-
var(El), !,
'$do_error'(instantiation_error,atom_list_concat(L,El,At)).
@ -119,6 +161,14 @@ atomic_list_concat(L, El, At) :-
'$subtract_lists_of_variables'([V1|VL1],[V2|VL2],[V2|VL]) :-
'$subtract_lists_of_variables'([V1|VL1],VL2,VL).
/** @pred current_atom( _A_)
Checks whether _A_ is a currently defined atom. It is used to find all
currently defined atoms by backtracking.
*/
current_atom(A) :- % check
atom(A), !.
current_atom(A) :- % generate
@ -165,3 +215,6 @@ string_concat(Xs,At) :-
Follow is Next+Sz,
'$process_string_holes'(Unbound).
/**
@}
*/

View File

@ -15,6 +15,122 @@
* *
*************************************************************************/
/** @defgroup Attributed_Variables Attributed Variables
@ingroup YAPExtensions
YAP supports attributed variables, originally developed at OFAI by
Christian Holzbaur. Attributes are a means of declaring that an
arbitrary term is a property for a variable. These properties can be
updated during forward execution. Moreover, the unification algorithm is
aware of attributed variables and will call user defined handlers when
trying to unify these variables.
Attributed variables provide an elegant abstraction over which one can
extend Prolog systems. Their main application so far has been in
implementing constraint handlers, such as Holzbaur's CLPQR, Fruewirth
and Holzbaur's CHR, and CLP(BN).
Different Prolog systems implement attributed variables in different
ways. Traditionally, YAP has used the interface designed by SICStus
Prolog. This interface is still
available in the <tt>atts</tt> library, but from YAP-6.0.3 we recommend using
the hProlog, SWI style interface. The main reason to do so is that
most packages included in YAP that use attributed variables, such as CHR, CLP(FD), and CLP(QR),
rely on the SWI-Prolog interface.
*/
/** @defgroup New_Style_Attribute_Declarations hProlog and SWI-Prolog style Attribute Declarations
@ingroup Attributed_Variables
@{
The following documentation is taken from the SWI-Prolog manual.
Binding an attributed variable schedules a goal to be executed at the
first possible opportunity. In the current implementation the hooks are
executed immediately after a successful unification of the clause-head
or successful completion of a foreign language (built-in) predicate. Each
attribute is associated to a module and the hook attr_unify_hook/2 is
executed in this module. The example below realises a very simple and
incomplete finite domain reasoner.
~~~~~
:- module(domain,
[ domain/2 % Var, ?Domain
]).
:- use_module(library(ordsets)).
domain(X, Dom) :-
var(Dom), !,
get_attr(X, domain, Dom).
domain(X, List) :-
list_to_ord_set(List, Domain),
put_attr(Y, domain, Domain),
X = Y.
% An attributed variable with attribute value Domain has been
% assigned the value Y
attr_unify_hook(Domain, Y) :-
( get_attr(Y, domain, Dom2)
-> ord_intersection(Domain, Dom2, NewDomain),
( NewDomain == []
-> fail
; NewDomain = [Value]
-> Y = Value
; put_attr(Y, domain, NewDomain)
)
; var(Y)
-> put_attr( Y, domain, Domain )
; ord_memberchk(Y, Domain)
).
% Translate attributes from this module to residual goals
attribute_goals(X) -->
{ get_attr(X, domain, List) },
[domain(X, List)].
~~~~~
Before explaining the code we give some example queries:
The predicate `domain/2` fetches (first clause) or assigns
(second clause) the variable a <em>domain</em>, a set of values it can
be unified with. In the second clause first associates the domain
with a fresh variable and then unifies X to this variable to deal
with the possibility that X already has a domain. The
predicate attr_unify_hook/2 is a hook called after a variable with
a domain is assigned a value. In the simple case where the variable
is bound to a concrete value we simply check whether this value is in
the domain. Otherwise we take the intersection of the domains and either
fail if the intersection is empty (first example), simply assign the
value if there is only one value in the intersection (second example) or
assign the intersection as the new domain of the variable (third
example). The nonterminal `attribute_goals/3` is used to translate
remaining attributes to user-readable goals that, when executed, reinstate
these attributes.
@pred put_attr(+ _Var_,+ _Module_,+ _Value_)
If _Var_ is a variable or attributed variable, set the value for the
attribute named _Module_ to _Value_. If an attribute with this
name is already associated with _Var_, the old value is replaced.
Backtracking will restore the old value (i.e., an attribute is a mutable
term. See also `setarg/3`). This predicate raises a representation error if
_Var_ is not a variable and a type error if _Module_ is not an atom.
*/
:- module('$attributes', [
delayed_goals/4
]).
@ -41,6 +157,17 @@
:- dynamic attributes:attributed_module/3, attributes:modules_with_attributes/1.
/** @pred get_attr(+ _Var_,+ _Module_,- _Value_)
Request the current _value_ for the attribute named _Module_. If
_Var_ is not an attributed variable or the named attribute is not
associated to _Var_ this predicate fails silently. If _Module_
is not an atom, a type error is raised.
*/
prolog:get_attr(Var, Mod, Att) :-
functor(AttTerm, Mod, 2),
arg(2, AttTerm, Att),
@ -51,16 +178,45 @@ prolog:put_attr(Var, Mod, Att) :-
arg(2, AttTerm, Att),
attributes:put_module_atts(Var, AttTerm).
/** @pred del_attr(+ _Var_,+ _Module_)
Delete the named attribute. If _Var_ loses its last attribute it
is transformed back into a traditional Prolog variable. If _Module_
is not an atom, a type error is raised. In all other cases this
predicate succeeds regardless whether or not the named attribute is
present.
*/
prolog:del_attr(Var, Mod) :-
functor(AttTerm, Mod, 2),
attributes:del_all_module_atts(Var, AttTerm).
/** @pred del_attrs(+ _Var_)
If _Var_ is an attributed variable, delete <em>all</em> its
attributes. In all other cases, this predicate succeeds without
side-effects.
*/
prolog:del_attrs(Var) :-
attributes:del_all_atts(Var).
prolog:get_attrs(AttVar, SWIAtts) :-
attributes:get_all_swi_atts(AttVar,SWIAtts).
/** @pred put_attrs(+ _Var_,+ _Attributes_)
Set all attributes of _Var_. See get_attrs/2 for a description of
_Attributes_.
*/
prolog:put_attrs(_, []).
prolog:put_attrs(V, Atts) :-
cvt_to_swi_atts(Atts, YapAtts),
@ -170,6 +326,26 @@ lcall2([Goal|Goals], Mod) :-
/** @pred call_residue_vars(: _G_, _L_)
Call goal _G_ and unify _L_ with a list of all constrained variables created <em>during</em> execution of _G_:
~~~~~
?- dif(X,Z), call_residue_vars(dif(X,Y),L).
dif(X,Z), call_residue_vars(dif(X,Y),L).
L = [Y],
dif(X,Z),
dif(X,Y) ? ;
no
~~~~~
*/
prolog:call_residue_vars(Goal,Residue) :-
attributes:all_attvars(Vs0),
call(Goal),
@ -202,6 +378,22 @@ prolog:call_residue_vars(Goal,Residue) :-
% defined in the modules the attributes stem from, is used to
% convert attributes to lists of goals.
/** @pred copy_term(? _TI_,- _TF_,- _Goals_)
Term _TF_ is a variant of the original term _TI_, such that for
each variable _V_ in the term _TI_ there is a new variable _V'_
in term _TF_ without any attributes attached. Attributed
variables are thus converted to standard variables. _Goals_ is
unified with a list that represents the attributes. The goal
`maplist(call, _Goals_)` can be called to recreate the
attributes.
Before the actual copying, `copy_term/3` calls
`attribute_goals/1` in the module where the attribute is
defined.
*/
prolog:copy_term(Term, Copy, Gs) :-
term_attvars(Term, Vs),
( Vs == []
@ -224,6 +416,11 @@ attvars_residuals([V|Vs]) -->
),
attvars_residuals(Vs).
/** @pred _Module_:attribute_goal( _-Var_, _-Goal_)
User-defined procedure, called to convert the attributes in _Var_ to
a _Goal_. Should fail when no interpretation is available.
*/
attvar_residuals([], _) --> [].
attvar_residuals(att(Module,Value,As), V) -->
( { nonvar(V) }
@ -272,6 +469,35 @@ delete_attributes_([V|Vs]) :-
/** @pred call_residue(: _G_, _L_)
Call goal _G_. If subgoals of _G_ are still blocked, return
a list containing these goals and the variables they are blocked in. The
goals are then considered as unblocked. The next example shows a case
where dif/2 suspends twice, once outside call_residue/2,
and the other inside:
~~~~~
?- dif(X,Y),
call_residue((dif(X,Y),(X = f(Z) ; Y = f(Z))), L).
X = f(Z),
L = [[Y]-dif(f(Z),Y)],
dif(f(Z),Y) ? ;
Y = f(Z),
L = [[X]-dif(X,f(Z))],
dif(X,f(Z)) ? ;
no
~~~~~
The system only reports one invocation of dif/2 as having
suspended.
*/
prolog:call_residue(Goal,Residue) :-
var(Goal), !,
'$do_error'(instantiation_error,call_residue(Goal,Residue)).
@ -322,6 +548,28 @@ att_vars([_|LGs], AttVars) :-
% make sure we set the suspended goal list to its previous state!
% make sure we have installed a SICStus like constraint solver.
/** @pred _Module_:project_attributes( _+QueryVars_, _+AttrVars_)
Given a list of variables _QueryVars_ and list of attributed
variables _AttrVars_, project all attributes in _AttrVars_ to
_QueryVars_. Although projection is constraint system dependent,
typically this will involve expressing all constraints in terms of
_QueryVars_ and considering all remaining variables as existentially
quantified.
Projection interacts with attribute_goal/2 at the Prolog top
level. When the query succeeds, the system first calls
project_attributes/2. The system then calls
attribute_goal/2 to get a user-level representation of the
constraints. Typically, attribute_goal/2 will convert from the
original constraints into a set of new constraints on the projection,
and these constraints are the ones that will have an
attribute_goal/2 handler.
*/
project_attributes(AllVs, G) :-
attributes:modules_with_attributes(LMods),
LMods = [_|_],
@ -344,3 +592,6 @@ project_module([Mod|LMods], LIV, LAV) :-
project_module([_|LMods], LIV, LAV) :-
project_module(LMods,LIV,LAV).
/**
@}
*/

281
pl/boot.yap Executable file → Normal file
View File

@ -15,6 +15,15 @@
* *
*************************************************************************/
/**
@defgroup YAPControl Control Predicates
@ingroup YAPBuiltins
@{
*/
/** @pred :_P_ , :_Q_ is iso
@ -130,7 +139,6 @@ arguments.
/** @pred :_Condition_ *-> :_Action_
This construct implements the so-called <em>soft-cut</em>. The control is
defined as follows: If _Condition_ succeeds at least once, the
semantics is the same as ( _Condition_, _Action_). If
@ -139,7 +147,7 @@ semantics is the same as ( _Condition_, _Action_). If
succeeds at least once, simply behave as the conjunction of
_Condition_ and _Action_, otherwise execute _Else_.
The construct _A \*-> B_, i.e. without an _Else_ branch, is
The construct _A *-> B_, i.e. without an _Else_ branch, is
translated as the normal conjunction _A_, _B_.
@ -179,7 +187,6 @@ definition:
the same query would return only the first element of the
list, since backtracking could not "pass through" the cut.
*/
@ -292,6 +299,13 @@ private(_).
%
%
%
/** @pred true is iso
Succeeds once.
*/
true :- true.
'$live' :-
@ -531,6 +545,30 @@ true :- true.
fail.
'$version'.
/** @pred repeat is iso
Succeeds repeatedly.
In the next example, `repeat` is used as an efficient way to implement
a loop. The next example reads all terms in a file:
~~~~~~~~~~~~~{.prolog}
a :- repeat, read(X), write(X), nl, X=end_of_file, !.
~~~~~~~~~~~~~
the loop is effectively terminated by the cut-goal, when the test-goal
`X=end` succeeds. While the test fails, the goals `read(X)`,
`write(X)`, and `nl` are executed repeatedly, because
backtracking is caught by the `repeat` goal.
The built-in `repeat/0` could be defined in Prolog by:
~~~~~{.prolog}
repeat.
repeat :- repeat.
~~~~~
The predicate between/3 can be used to iterate for a pre-defined
number of steps.
*/
repeat :- '$repeat'.
'$repeat'.
@ -1014,8 +1052,45 @@ true :- true.
format(user_error,' = ~s',[V]),
'$write_output_vars'(VL).
/** @pred + _P_ is nondet
The same as `call( _P_)`. This feature has been kept to provide
compatibility with C-Prolog. When compiling a goal, YAP
generates a `call( _X_)` whenever a variable _X_ is found as
a goal.
~~~~~{.prolog}
a(X) :- X.
~~~~~
is converted to:
~~~~~{.prolog}
a(X) :- call(X).
~~~~~
*/
/** @pred call(+ _P_) is iso
Meta-call predicate.
If _P_ is instantiated to an atom or a compound term, the goal `call(
_P_)` is executed as if the clause was originally written as _P_
instead as call( _P_ ), except that any "cut" occurring in _P_ only
cuts alternatives in the execution of _P_.
*/
call(G) :- '$execute'(G).
/** @pred incore(+ _P_)
The same as call/1.
*/
incore(G) :- '$execute'(G).
%
@ -1214,70 +1289,6 @@ not(G) :- \+ '$execute'(G).
'$do_error'(type_error(callable,R),G).
'$check_callable'(_,_).
% Called by the abstract machine, if no clauses exist for a predicate
'$undefp'([M|G]) :-
'$find_goal_definition'(M, G, NM, NG),
'$execute0'(NG, NM).
'$find_goal_definition'(M, G, NM, NG) :-
% make sure we do not loop on undefined predicates
% for undefined_predicates.
'$enter_undefp',
(
'$get_undefined_pred'(G, M, Goal, NM)
->
'$exit_undefp',
Goal \= fail,
'$complete_goal'(M, Goal, NM, G, NG)
;
'$find_undefp_handler'(G, M),
NG = G, NM = M
).
'$complete_goal'(M, G, CurMod, G0, NG) :-
(
'$is_metapredicate'(G,CurMod)
->
'$meta_expansion'(G, CurMod, M, M, NG,[])
;
NG = G
).
'$find_undefp_handler'(G,M,NG,user) :-
functor(G, Na, Ar),
user:exception(undefined_predicate,M:Na/Ar,Action), !,
'$exit_undefp',
(
Action == fail
->
NG = fail
;
Action == retry
->
NG = G
;
Action == error
->
'$unknown_error'(M:G)
;
'$do_error'(type_error(atom, Action),M:G)
).
'$find_undefp_handler'(G,M) :-
'$exit_undefp',
'$swi_current_prolog_flag'(M:unknown, Action),
(
Action == fail
->
fail
;
Action == warning
->
'$unknown_warning'(M:G),
fail
;
'$unknown_error'(M:G)
).
'$silent_bootstrap'(F) :-
'$init_globals',
@ -1394,6 +1405,20 @@ bootstrap(F) :-
'$precompile_term'(Term, Term, Term, _, _).
/** @pred expand_term( _T_,- _X_)
This predicate is used by YAP for preprocessing each top level
term read when consulting a file and before asserting or executing it.
It rewrites a term _T_ to a term _X_ according to the following
rules: first try term_expansion/2 in the current module, and then try to use the user defined predicate
`user:term_expansion/2`. If this call fails then the translating process
for DCG rules is applied, together with the arithmetic optimizer
whenever the compilation of arithmetic expressions is in progress.
*/
expand_term(Term,Expanded) :-
( '$do_term_expansion'(Term,Expanded)
->
@ -1424,6 +1449,21 @@ expand_term(Term,Expanded) :-
% at each catch point I need to know:
% what is ball;
% where was the previous catch
/** @pred catch( : _Goal_,+ _Exception_,+ _Action_) is iso
The goal `catch( _Goal_, _Exception_, _Action_)` tries to
execute goal _Goal_. If during its execution, _Goal_ throws an
exception _E'_ and this exception unifies with _Exception_, the
exception is considered to be caught and _Action_ is executed. If
the exception _E'_ does not unify with _Exception_, control
again throws the exception.
The top-level of YAP maintains a default exception handler that
is responsible to capture uncaught exceptions.
*/
catch(G, C, A) :-
'$catch'(C,A,_),
'$$save_by'(CP0),
@ -1451,6 +1491,16 @@ catch(G, C, A) :-
%
% throw has to be *exactly* after system catch!
%
/** @pred throw(+ _Ball_) is iso
The goal `throw( _Ball_)` throws an exception. Execution is
stopped, and the exception is sent to the ancestor goals until reaching
a matching catch/3, or until reaching top-level.
@}
*/
throw(_Ball) :-
% use existing ball
'$get_exception'(Ball),
@ -1480,7 +1530,7 @@ throw(Ball) :-
).
catch_ball(Abort, _) :- Abort == '$abort', !, fail.
% system defined throws should be ignored by used, unless the
% system defined throws should be ignored by user, unless the
% user is hacking away.
catch_ball(Ball, V) :-
var(V),
@ -1508,3 +1558,98 @@ log_event( String, Args ) :-
format( atom( M ), String, Args),
log_event( M ).
/**
@}
*/
/** @defgroup Undefined_Procedures Handling Undefined Procedures
@ingroup YAPControl
@{
A predicate in a module is said to be undefined if there are no clauses
defining the predicate, and if the predicate has not been declared to be
dynamic. What YAP does when trying to execute undefined predicates can
be specified in three different ways:
+ By setting an YAP flag, through the yap_flag/2 or
set_prolog_flag/2 built-ins. This solution generalizes the
ISO standard.
+ By using the unknown/2 built-in (this solution is
compatible with previous releases of YAP).
+ By defining clauses for the hook predicate
`user:unknown_predicate_handler/3`. This solution is compatible
with SICStus Prolog.
*/
% Called by the abstract machine, if no clauses exist for a predicate
'$undefp'([M|G]) :-
'$find_goal_definition'(M, G, NM, NG),
'$execute0'(NG, NM).
'$find_goal_definition'(M, G, NM, NG) :-
% make sure we do not loop on undefined predicates
% for undefined_predicates.
'$enter_undefp',
(
'$get_undefined_pred'(G, M, Goal, NM)
->
'$exit_undefp',
Goal \= fail,
'$complete_goal'(M, Goal, NM, G, NG)
;
'$find_undefp_handler'(G, M),
NG = G, NM = M
).
'$complete_goal'(M, G, CurMod, G0, NG) :-
(
'$is_metapredicate'(G,CurMod)
->
'$meta_expansion'(G, CurMod, M, M, NG,[])
;
NG = G
).
'$find_undefp_handler'(G,M,NG,user) :-
functor(G, Na, Ar),
user:exception(undefined_predicate,M:Na/Ar,Action), !,
'$exit_undefp',
(
Action == fail
->
NG = fail
;
Action == retry
->
NG = G
;
Action == error
->
'$unknown_error'(M:G)
;
'$do_error'(type_error(atom, Action),M:G)
).
'$find_undefp_handler'(G,M) :-
'$exit_undefp',
'$swi_current_prolog_flag'(M:unknown, Action),
(
Action == fail
->
fail
;
Action == warning
->
'$unknown_warning'(M:G),
fail
;
'$unknown_error'(M:G)
).
/**
@}
*/

View File

@ -15,6 +15,60 @@
* *
*************************************************************************/
/** @defgroup Profiling Profiling Prolog Programs
@ingroup YAPExtensions
@{
YAP includes two profilers. The count profiler keeps information on the
number of times a predicate was called. This information can be used to
detect what are the most commonly called predicates in the program. The
count profiler can be compiled by setting YAP's flag profiling
to `on`. The time-profiler is a `gprof` profiler, and counts
how many ticks are being spent on specific predicates, or on other
system functions such as internal data-base accesses or garbage collects.
The YAP profiling sub-system is currently under
development. Functionality for this sub-system will increase with newer
implementation.
*/
/**
@}
*/
/** @defgroup Call_Counting Counting Calls
@ingroup Profiling
@{
Predicates compiled with YAP's flag call_counting set to
`on` update counters on the numbers of calls and of
retries. Counters are actually decreasing counters, so that they can be
used as timers. Three counters are available:
+ `calls`: number of predicate calls since execution started or since
system was reset;
+ `retries`: number of retries for predicates called since
execution started or since counters were reset;
+ `calls_and_retries`: count both on predicate calls and
retries.
These counters can be used to find out how many calls a certain
goal takes to execute. They can also be used as timers.
The code for the call counters piggybacks on the profiling
code. Therefore, activating the call counters also activates the profiling
counters.
These are the predicates that access and manipulate the call counters:
*/
:- system_module( '$_callcount', [call_count/3,
call_count_data/3,
call_count_reset/0], []).
@ -22,12 +76,70 @@
:- use_system_module( '$_errors', ['$do_error'/2]).
/** @pred call_count_data(- _Calls_, - _Retries_, - _CallsAndRetries_)
Give current call count data. The first argument gives the current value
for the _Calls_ counter, next the _Retries_ counter, and last
the _CallsAndRetries_ counter.
*/
call_count_data(Calls, Retries, Both) :-
'$call_count_info'(Calls, Retries, Both).
/** @pred call_count_reset
Reset call count counters. All timers are also reset.
*/
call_count_reset :-
'$call_count_reset'.
/** @pred call_count(? _CallsMax_, ? _RetriesMax_, ? _CallsAndRetriesMax_)
Set call counters as timers. YAP will generate an exception
if one of the instantiated call counters decreases to 0:
+ _CallsMax_
throw the exception `call_counter` when the
counter `calls` reaches 0;
+ _RetriesMax_
throw the exception `retry_counter` when the
counter `retries` reaches 0;
+ _CallsAndRetriesMax_
throw the exception
`call_and_retry_counter` when the counter `calls_and_retries`
reaches 0.
YAP will ignore counters that are called with unbound arguments.
Next, we show a simple example of how to use call counters:
~~~~~{.prolog}
?- yap_flag(call_counting,on), [-user]. l :- l. end_of_file. yap_flag(call_counting,off).
yes
yes
?- catch((call_count(10000,_,_),l),call_counter,format("limit_exceeded.~n",[])).
limit_exceeded.
yes
~~~~~
Notice that we first compile the looping predicate `l/0` with
call_counting `on`. Next, we catch/3 to handle an
exception when `l/0` performs more than 10000 reductions.
*/
call_count(Calls, Retries, Both) :-
'$check_if_call_count_on'(Calls, CallsOn),
'$check_if_call_count_on'(Retries, RetriesOn),
@ -40,4 +152,7 @@ call_count(Calls, Retries, Both) :-
'$do_error'(type_error(integer,Calls),call_count(A)).
/**
@}
*/

68
pl/consult.yap Executable file → Normal file
View File

@ -67,7 +67,7 @@
/**
\defgroup YAPConsulting Loading files into YAP
@ingroup YAPProgramming
@ingroup YAPLoading
We present the main predicates and directives available to load
files and to set-up the Prolog environment. We discuss
@ -807,6 +807,72 @@ source_file(Mod:Pred, FileName) :-
'$owned_by'(T, Mod, FileName) :-
'$owner_file'(T, Mod, FileName).
/** @pred prolog_load_context(? _Key_, ? _Value_)
Obtain information on what is going on in the compilation process. The
following keys are available:
+ directory
Full name for the directory where YAP is currently consulting the
file.
+ file
Full name for the file currently being consulted. Notice that included
filed are ignored.
+ module
Current source module.
+ `source` (prolog_load_context/2 option)
Full name for the file currently being read in, which may be consulted,
reconsulted, or included.
+ `stream`
Stream currently being read in.
+ `term_position`
Stream position at the stream currently being read in. For SWI
compatibility, it is a term of the form
'$stream_position'(0,Line,0,0,0).
+ `source_location(? _FileName_, ? _Line_)`
SWI-compatible predicate. If the last term has been read from a physical file (i.e., not from the file user or a string), unify File with an absolute path to the file and Line with the line-number in the file. Please use prolog_load_context/2.
+ `source_file(? _File_)`
SWI-compatible predicate. True if _File_ is a loaded Prolog source file.
+ `source_file(? _ModuleAndPred_,? _File_)`
SWI-compatible predicate. True if the predicate specified by _ModuleAndPred_ was loaded from file _File_, where _File_ is an absolute path name (see `absolute_file_name/2`).
@section YAPLibraries Library Predicates
Library files reside in the library_directory path (set by the
`LIBDIR` variable in the Makefile for YAP). Currently,
most files in the library are from the Edinburgh Prolog library.
*/
prolog_load_context(directory, DirName) :-
source_location(F, _),
file_directory_name(F, DirName).

344
pl/control.yap Executable file → Normal file
View File

@ -1,4 +1,4 @@
/*************************************************************************
g/*************************************************************************
* *
* YAP Prolog *
* *
@ -15,6 +15,13 @@
* *
*************************************************************************/
/**
@addtogroup YAPControl
@{
*/
:- system_module( '$_control', [at_halt/1,
b_getval/2,
break/0,
@ -68,10 +75,69 @@
:- use_system_module( '$coroutining', [freeze_goal/2]).
/** @pred once(: _G_) is iso
Execute the goal _G_ only once. The predicate is defined by:
~~~~~{.prolog}
once(G) :- call(G), !.
~~~~~
Note that cuts inside once/1 can only cut the other goals inside
once/1.
*/
once(G) :- '$execute'(G), !.
/** @pred forall(: _Cond_,: _Action_)
For all alternative bindings of _Cond_ _Action_ can be
proven. The example verifies that all arithmetic statements in the list
_L_ are correct. It does not say which is wrong if one proves wrong.
~~~~~{.prolog}
?- forall(member(Result = Formula, [2 = 1 + 1, 4 = 2 * 2]),
Result =:= Formula).
~~~~~
*/
/** @pred forall(+ _Cond_,+ _Action_)
For all alternative bindings of _Cond_ _Action_ can be proven.
The next example verifies that all arithmetic statements in the list
_L_ are correct. It does not say which is wrong if one proves wrong.
~~~~~
?- forall(member(Result = Formula, [2 = 1 + 1, 4 = 2 * 2]),
Result =:= Formula).
~~~~~
*/
forall(Cond, Action) :- \+((Cond, \+(Action))).
/** @pred ignore(: _Goal_)
Calls _Goal_ as once/1, but succeeds, regardless of whether
`Goal` succeeded or not. Defined as:
~~~~~{.prolog}
ignore(Goal) :-
Goal, !.
ignore(_).
~~~~~
*/
ignore(Goal) :- (Goal->true;true).
notrace(G) :-
@ -87,6 +153,51 @@ notrace(G) :-
fail
).
/** @pred if(? _G_,? _H_,? _I_)
Call goal _H_ once per each solution of goal _H_. If goal
_H_ has no solutions, call goal _I_.
The built-in `if/3` is similar to `->/3`, with the difference
that it will backtrack over the test goal. Consider the following
small data-base:
~~~~~{.prolog}
a(1). b(a). c(x).
a(2). b(b). c(y).
~~~~~
Execution of an `if/3` query will proceed as follows:
~~~~~{.prolog}
?- if(a(X),b(Y),c(Z)).
X = 1,
Y = a ? ;
X = 1,
Y = b ? ;
X = 2,
Y = a ? ;
X = 2,
Y = b ? ;
no
~~~~~
The system will backtrack over the two solutions for `a/1` and the
two solutions for `b/1`, generating four solutions.
Cuts are allowed inside the first goal _G_, but they will only prune
over _G_.
If you want _G_ to be deterministic you should use if-then-else, as
it is both more efficient and more portable.
*/
if(X,Y,Z) :-
yap_hacks:env_choice_point(CP0),
(
@ -103,6 +214,15 @@ call(X,A) :- '$execute'(X,A).
call(X,A1,A2) :- '$execute'(X,A1,A2).
/** @pred call(+ _Closure_,...,? _Ai_,...) is iso
Meta-call where _Closure_ is a closure that is converted into a goal by
appending the _Ai_ additional arguments. The number of arguments varies
between 0 and 10.
*/
call(X,A1,A2,A3) :- '$execute'(X,A1,A2,A3).
call(X,A1,A2,A3,A4) :- '$execute'(X,A1,A2,A3,A4).
@ -121,15 +241,90 @@ call(X,A1,A2,A3,A4,A5,A6,A7,A8,A9,A10) :- '$execute'(X,A1,A2,A3,A4,A5,A6,A7,A8,A
call(X,A1,A2,A3,A4,A5,A6,A7,A8,A9,A10,A11) :- '$execute'(X,A1,A2,A3,A4,A5,A6,A7,A8,A9,A10,A11).
/** @pred call_cleanup(: _Goal_, : _CleanUpGoal_)
This is similar to <tt>call_cleanup/1</tt> with an additional
_CleanUpGoal_ which gets called after _Goal_ is finished.
*/
call_cleanup(Goal, Cleanup) :-
setup_call_catcher_cleanup(true, Goal, _Catcher, Cleanup).
call_cleanup(Goal, Catcher, Cleanup) :-
setup_call_catcher_cleanup(true, Goal, Catcher, Cleanup).
/** @pred setup_call_cleanup(: _Setup_,: _Goal_, : _CleanUpGoal_)
Calls `(Setup, Goal)`. For each sucessful execution of _Setup_, calling _Goal_, the
cleanup handler _Cleanup_ is guaranteed to be called exactly once.
This will happen after _Goal_ completes, either through failure,
deterministic success, commit, or an exception. _Setup_ will
contain the goals that need to be protected from asynchronous interrupts
such as the ones received from `call_with_time_limit/2` or thread_signal/2. In
most uses, _Setup_ will perform temporary side-effects required by
_Goal_ that are finally undone by _Cleanup_.
Success or failure of _Cleanup_ is ignored and choice-points it
created are destroyed (as once/1). If _Cleanup_ throws an exception,
this is executed as normal.
Typically, this predicate is used to cleanup permanent data storage
required to execute _Goal_, close file-descriptors, etc. The example
below provides a non-deterministic search for a term in a file, closing
the stream as needed.
~~~~~{.prolog}
term_in_file(Term, File) :-
setup_call_cleanup(open(File, read, In),
term_in_stream(Term, In),
close(In) ).
term_in_stream(Term, In) :-
repeat,
read(In, T),
( T == end_of_file
-> !, fail
; T = Term
).
~~~~~
Note that it is impossible to implement this predicate in Prolog other than
by reading all terms into a list, close the file and call member/2.
Without setup_call_cleanup/3 there is no way to gain control if the
choice-point left by `repeat` is removed by a cut or an exception.
`setup_call_cleanup/2` can also be used to test determinism of a goal:
~~~~~
?- setup_call_cleanup(true,(X=1;X=2), Det=yes).
X = 1 ;
X = 2,
Det = yes ;
~~~~~
This predicate is under consideration for inclusion into the ISO standard.
For compatibility with other Prolog implementations see `call_cleanup/2`.
*/
setup_call_cleanup(Setup, Goal, Cleanup) :-
setup_call_catcher_cleanup(Setup, Goal, _Catcher, Cleanup).
/** @pred setup_call_catcher_cleanup(: _Setup_,: _Goal_, + _Catcher_,: _CleanUpGoal_)
Similar to `setup_call_cleanup( _Setup_, _Goal_, _Cleanup_)` with
additional information on the reason of calling _Cleanup_. Prior
to calling _Cleanup_, _Catcher_ unifies with the termination
code. If this unification fails, _Cleanup_ is
*not* called.
*/
setup_call_catcher_cleanup(Setup, Goal, Catcher, Cleanup) :-
yap_hacks:disable_interrupts,
'$check_goal_for_setup_call_cleanup'(Setup, setup_call_cleanup(Setup, Goal, Cleanup)),
@ -218,7 +413,19 @@ setup_call_catcher_cleanup(Setup, Goal, Catcher, Cleanup) :-
% this predicate shows the code produced by the compiler
'$show_code' :- '$debug'(0'f). %' just make emacs happy
/** @pred grow_heap(+ _Size_)
Increase heap size _Size_ kilobytes.
*/
grow_heap(X) :- '$grow_heap'(X).
/** @pred grow_stack(+ _Size_)
Increase stack size _Size_ kilobytes
*/
grow_stack(X) :- '$grow_stack'(X).
%
@ -226,13 +433,44 @@ grow_stack(X) :- '$grow_stack'(X).
% environment to return to.
%
%garbage_collect :- save(dump), '$gc', save(dump2).
/** @pred garbage_collect
The goal `garbage_collect` forces a garbage collection.
*/
garbage_collect :-
'$gc'.
/** @pred gc
The goal `gc` enables garbage collection. The same as
`yap_flag(gc,on)`.
*/
gc :-
yap_flag(gc,on).
/** @pred nogc
The goal `nogc` disables garbage collection. The same as
`yap_flag(gc,off)`.
*/
nogc :-
yap_flag(gc,off).
/** @pred garbage_collect_atoms
The goal `garbage_collect` forces a garbage collection of the atoms
in the data-base. Currently, only atoms are recovered.
*/
garbage_collect_atoms :-
'$atom_gc'.
@ -247,6 +485,14 @@ garbage_collect_atoms :-
'$good_character_code'(X) :- var(X), !.
'$good_character_code'(X) :- integer(X), X > -2, X < 256.
/** @pred prolog_initialization( _G_)
Add a goal to be executed on system initialization. This is compatible
with SICStus Prolog's initialization/1.
*/
prolog_initialization(G) :- var(G), !,
'$do_error'(instantiation_error,initialization(G)).
prolog_initialization(T) :- callable(T), !,
@ -257,8 +503,21 @@ prolog_initialization(T) :-
'$assert_init'(T) :- recordz('$startup_goal',T,_), fail.
'$assert_init'(_).
/** @pred version
Write YAP's boot message.
*/
version :- '$version'.
/** @pred version(- _Message_)
Add a message to be written when yap boots or after aborting. It is not
possible to remove messages.
*/
version(V) :- var(V), !,
'$do_error'(instantiation_error,version(V)).
version(T) :- atom(T), !, '$assert_version'(T).
@ -277,6 +536,28 @@ version(T) :-
fail.
'$set_toplevel_hook'(_).
/** @pred nb_getval(+ _Name_, - _Value_)
The nb_getval/2 predicate is a synonym for b_getval/2,
introduced for compatibility and symmetry. As most scenarios will use
a particular global variable either using non-backtrackable or
backtrackable assignment, using nb_getval/2 can be used to
document that the variable is used non-backtrackable.
*/
/** @pred nb_getval(+ _Name_,- _Value_)
The nb_getval/2 predicate is a synonym for b_getval/2, introduced for
compatibility and symmetry. As most scenarios will use a particular
global variable either using non-backtrackable or backtrackable
assignment, using nb_getval/2 can be used to document that the
variable is used non-backtrackable.
*/
nb_getval(GlobalVariable, Val) :-
'$nb_getval'(GlobalVariable, Val, Error),
(var(Error)
@ -290,6 +571,32 @@ nb_getval(GlobalVariable, Val) :-
).
/** @pred b_getval(+ _Name_, - _Value_)
Get the value associated with the global variable _Name_ and unify
it with _Value_. Note that this unification may further
instantiate the value of the global variable. If this is undesirable
the normal precautions (double negation or copy_term/2) must be
taken. The b_getval/2 predicate generates errors if _Name_ is not
an atom or the requested variable does not exist.
Notice that for compatibility with other systems _Name_ <em>must</em> be already associated with a term: otherwise the system will generate an error.
*/
/** @pred b_getval(+ _Name_,- _Value_)
Get the value associated with the global variable _Name_ and unify
it with _Value_. Note that this unification may further instantiate
the value of the global variable. If this is undesirable the normal
precautions (double negation or copy_term/2) must be taken. The
b_getval/2 predicate generates errors if _Name_ is not an atom or
the requested variable does not exist.
*/
b_getval(GlobalVariable, Val) :-
'$nb_getval'(GlobalVariable, Val, Error),
(var(Error)
@ -333,6 +640,22 @@ b_getval(GlobalVariable, Val) :-
b_setval('$trace',Trace),
'$enable_debugging'.
/** @pred break
Suspends the execution of the current goal and creates a new execution
level similar to the top level, displaying the following message:
~~~~~{.prolog}
[ Break (level <number>) ]
~~~~~
telling the depth of the break level just entered. To return to the
previous level just type the end-of-file character or call the
end_of_file predicate. This predicate is especially useful during
debugging.
*/
break :-
'$init_debugger',
nb_getval('$trace',Trace),
@ -367,12 +690,27 @@ at_halt(G) :-
fail.
at_halt(_).
/** @pred halt is iso
Halts Prolog, and exits to the calling application. In YAP,
halt/0 returns the exit code `0`.
*/
halt :-
print_message(informational, halt),
fail.
halt :-
'$halt'(0).
/** @pred halt(+ _I_) is iso
Halts Prolog, and exits to the calling application returning the code
given by the integer _I_.
*/
halt(_) :-
recorded('$halt', G, _),
call(G),
@ -395,4 +733,6 @@ prolog_current_frame(Env) :-
'$add_dot_to_atom_goal'([C|Gs0],[C|Gs]) :-
'$add_dot_to_atom_goal'(Gs0,Gs).
/**
@}
*/

View File

@ -16,6 +16,41 @@
*************************************************************************/
/** @defgroup CohYroutining Co-routining
@ingroup YAPExtensions
@{
Prolog uses a simple left-to-right flow of control. It is sometimes
convenient to change this control so that goals will only be executed
when conditions are fulfilled. This may result in a more "data-driven"
execution, or may be necessary to correctly implement extensions such as
negation by default.
The `COROUTINING` flag enables this option. Note that the support for
coroutining will in general slow down execution.
The following declaration is supported:
+ block/1
The argument to `block/1` is a condition on a goal or a conjunction
of conditions, with each element separated by commas. Each condition is
of the form `predname( _C1_,..., _CN_)`, where _N_ is the
arity of the goal, and each _CI_ is of the form `-`, if the
argument must suspend until the first such variable is bound, or
`?`, otherwise.
+ wait/1
The argument to `wait/1` is a predicate descriptor or a conjunction
of these predicates. These predicates will suspend until their first
argument is bound.
The following primitives are supported:
*/
:- module('$coroutining',[
op(1150, fx, block)
%dif/2,
@ -33,6 +68,23 @@
put_module_atts/2]).
/** @pred attr_unify_hook(+ _AttValue_,+ _VarValue_)
Hook that must be defined in the module an attributed variable refers
to. Is is called <em>after</em> the attributed variable has been
unified with a non-var term, possibly another attributed variable.
_AttValue_ is the attribute that was associated to the variable
in this module and _VarValue_ is the new value of the variable.
Normally this predicate fails to veto binding the variable to
_VarValue_, forcing backtracking to undo the binding. If
_VarValue_ is another attributed variable the hook often combines
the two attribute and associates the combined attribute with
_VarValue_ using put_attr/3.
*/
attr_unify_hook(DelayList, _) :-
wake_delays(DelayList).
@ -53,6 +105,32 @@ wake_delay(redo_eq(Done, X, Y, Goal)) :-
wake_delay(redo_ground(Done, X, Goal)) :-
redo_ground(Done, X, Goal).
/** @pred attribute_goals(+ _Var_,- _Gs_,+ _GsRest_)
This nonterminal, if it is defined in a module, is used by _copy_term/3_
to project attributes of that module to residual goals. It is also
used by the toplevel to obtain residual goals after executing a query.
Normal user code should deal with put_attr/3, get_attr/3 and del_attr/2.
The routines in this section fetch or set the entire attribute list of a
variables. Use of these predicates is anticipated to be restricted to
printing and other special purpose operations.
@pred get_attrs(+ _Var_,- _Attributes_)
Get all attributes of _Var_. _Attributes_ is a term of the form
`att( _Module_, _Value_, _MoreAttributes_)`, where _MoreAttributes_ is
`[]` for the last attribute.
*/
attribute_goals(Var) -->
{ get_attr(Var, '$coroutining', Delays) },
attgoal_for_delays(Delays, Var).
@ -84,6 +162,13 @@ remove_when_declarations(Goal, Goal).
%
% operators defined in this module:
%
/** @pred freeze(? _X_,: _G_)
Delay execution of goal _G_ until the variable _X_ is bound.
*/
prolog:freeze(V, G) :-
var(V), !,
freeze_goal(V,G).
@ -136,6 +221,15 @@ freeze_goal(V,G) :-
% several times. dif calls a special version of freeze that checks
% whether that is in fact the case.
%
/** @pred dif( _X_, _Y_)
Succeed if the two arguments do not unify. A call to dif/2 will
suspend if unification may still succeed or fail, and will fail if they
always unify.
*/
prolog:dif(X, Y) :-
'$can_unify'(X, Y, LVars), !,
LVars = [_|_],
@ -213,6 +307,28 @@ redo_ground('$done', _, Goal) :-
%
% support for when/2 built-in
%
/** @pred when(+ _C_,: _G_)
Delay execution of goal _G_ until the conditions _C_ are
satisfied. The conditions are of the following form:
+ _C1_, _C2_
Delay until both conditions _C1_ and _C2_ are satisfied.
+ _C1_; _C2_
Delay until either condition _C1_ or condition _C2_ is satisfied.
+ ?=( _V1_, _C2_)
Delay until terms _V1_ and _V1_ have been unified.
+ nonvar( _V_)
Delay until variable _V_ is bound.
+ ground( _V_)
Delay until variable _V_ is ground.
Note that when/2 will fail if the conditions fail.
*/
prolog:when(Conds,Goal) :-
'$current_module'(Mod),
prepare_goal_for_when(Goal, Mod, ModG),
@ -446,6 +562,14 @@ prolog:'$wait'(Na/Ar) :-
'$$compile'((S :- var(A), !, freeze(A, S)), (S :- var(A), !, freeze(A, S)), 5, M), fail.
prolog:'$wait'(_).
/** @pred frozen( _X_, _G_)
Unify _G_ with a conjunction of goals suspended on variable _X_,
or `true` if no goal has suspended.
*/
prolog:frozen(V, LG) :-
var(V), !,
'$attributes':attvars_residuals([V], Gs, []),
@ -493,3 +617,6 @@ check_first_attvar(V.Vs, V0) :- attvar(V), !, V == V0.
check_first_attvar(_.Vs, V0) :-
check_first_attvar(Vs, V0).
/**
@}
*/

View File

@ -45,6 +45,33 @@
-----------------------------------------------------------------------------*/
/** @defgroup Deb_Preds Debugging Predicates
@ingroup YAPBuiltins
@{
The
following predicates are available to control the debugging of
programs:
+ debug
Switches the debugger on.
+ debugging
Outputs status information about the debugger which includes the leash
mode and the existing spy-points, when the debugger is on.
+ nodebug
Switches the debugger off.
*/
:- op(900,fx,[spy,nospy]).
'$init_debugger' :-
@ -156,6 +183,18 @@
'$pred_being_spied'(G, M) :-
recorded('$spy','$spy'(G,M),_), !.
/** @pred spy( + _P_ ).
Sets spy-points on all the predicates represented by
_P_. _P_ can either be a single specification or a list of
specifications. Each one must be of the form _Name/Arity_
or _Name_. In the last case all predicates with the name
_Name_ will be spied. As in C-Prolog, system predicates and
predicates written in C, cannot be spied.
*/
spy Spec :-
'$init_debugger',
prolog:debug_action_hook(spy(Spec)), !.
@ -164,6 +203,14 @@
'$suspy'(L, spy, M), fail.
spy _ :- debug.
/** @pred nospy( + _P_ )
Removes spy-points from all predicates specified by _P_.
The possible forms for _P_ are the same as in `spy P`.
*/
nospy Spec :-
'$init_debugger',
prolog:debug_action_hook(nospy(Spec)), !.
@ -172,6 +219,13 @@
'$suspy'(L, nospy, M), fail.
nospy _.
/** @pred nospyall
Removes all existing spy-points.
*/
nospyall :-
'$init_debugger',
prolog:debug_action_hook(nospyall), !.
@ -206,6 +260,14 @@
% remove any debugging info after an abort.
%
/** @pred trace
Switches on the debugger and enters tracing mode.
*/
trace :-
'$init_debugger',
'$nb_getval'('$trace', on, fail), !.
@ -215,6 +277,16 @@ trace :-
print_message(informational,debug(trace)),
'$creep'.
/** @pred notrace
Ends tracing and exits the debugger. This is the same as
nodebug/0.
*/
notrace :-
'$init_debugger',
nodebug.
@ -226,6 +298,55 @@ notrace :-
-----------------------------------------------------------------------------*/
/** @pred leash(+ _M_)
Sets leashing mode to _M_.
The mode can be specified as:
+ `full`
prompt on Call, Exit, Redo and Fail
+ `tight`
prompt on Call, Redo and Fail
+ `half`
prompt on Call and Redo
+ `loose`
prompt on Call
+ `off`
never prompt
+ `none`
never prompt, same as `off`
The initial leashing mode is `full`.
The user may also specify directly the debugger ports
where he wants to be prompted. If the argument for leash
is a number _N_, each of lower four bits of the number is used to
control prompting at one the ports of the box model. The debugger will
prompt according to the following conditions:
+ if `N/\ 1 =\= 0` prompt on fail
+ if `N/\ 2 =\= 0` prompt on redo
+ if `N/\ 4 =\= 0` prompt on exit
+ if `N/\ 8 =\= 0` prompt on call
Therefore, `leash(15)` is equivalent to `leash(full)` and
`leash(0)` is equivalent to `leash(off)`.
Another way of using `leash` is to give it a list with the names of
the ports where the debugger should stop. For example,
`leash([call,exit,redo,fail])` is the same as `leash(full)` or
`leash(15)` and `leash([fail])` might be used instead of
`leash(1)`.
@}
*/
leash(X) :- var(X),
'$do_error'(instantiation_error,leash(X)).
leash(X) :-
@ -276,6 +397,7 @@ leash(X) :-
-----------------------------------------------------------------------------*/
debugging :-
'$init_debugger',
prolog:debug_action_hook(nospyall), !.
@ -290,6 +412,228 @@ debugging :-
get_value('$leash',Leash),
'$show_leash'(help,Leash).
/*
@}
*/
/** @defgroup Deb_Interaction Interacting with the debugger
@ingroup YAPProgramming
Debugging with YAP is similar to debugging with C-Prolog. Both systems
include a procedural debugger, based on Byrd's four port model. In this
model, execution is seen at the procedure level: each activation of a
procedure is seen as a box with control flowing into and out of that
box.
In the four port model control is caught at four key points: before
entering the procedure, after exiting the procedure (meaning successful
evaluation of all queries activated by the procedure), after backtracking but
before trying new alternative to the procedure and after failing the
procedure. Each one of these points is named a port:
~~~~~
*--------------------------------------*
Call | | Exit
---------> + descendant(X,Y) :- offspring(X,Y). + --------->
| |
| descendant(X,Z) :- |
<--------- + offspring(X,Y), descendant(Y,Z). + <---------
Fail | | Redo
*--------------------------------------*
~~~~~
+ `Call`
The call port is activated before initial invocation of
procedure. Afterwards, execution will try to match the goal with the
head of existing clauses for the procedure.
+ `Exit`
This port is activated if the procedure succeeds.
Control will now leave the procedure and return to its ancestor.
+ `Redo`
If the goal, or goals, activated after the call port
fail then backtracking will eventually return control to this procedure
through the redo port.
+ `Fail`
If all clauses for this predicate fail, then the
invocation fails, and control will try to redo the ancestor of this
invocation.
To start debugging, the user will either call `trace` or spy the
relevant procedures, entering debug mode, and start execution of the
program. When finding the first spy-point, YAP's debugger will take
control and show a message of the form:
~~~~~
* (1) call: quicksort([1,2,3],_38) ?
~~~~~
The debugger message will be shown while creeping, or at spy-points,
and it includes four or five fields:
+
The first three characters are used to point out special states of the
debugger. If the port is exit and the first character is '?', the
current call is non-deterministic, that is, it still has alternatives to
be tried. If the second character is a `\*`, execution is at a
spy-point. If the third character is a `>`, execution has returned
either from a skip, a fail or a redo command.
+
The second field is the activation number, and uniquely identifies the
activation. The number will start from 1 and will be incremented for
each activation found by the debugger.
+
In the third field, the debugger shows the active port.
+
The fourth field is the goal. The goal is written by
`write_term/3` on the standard error stream, using the options
given by debugger_print_options.
If the active port is leashed, the debugger will prompt the user with a
`?`, and wait for a command. A debugger command is just a
character, followed by a return. By default, only the call and redo
entries are leashed, but the leash/1 predicate can be used in
order to make the debugger stop where needed.
There are several commands available, but the user only needs to
remember the help command, which is `h`. This command shows all the
available options, which are:
+ `c` - creep
this command makes YAP continue execution and stop at the next
leashed port.
+ `return` - creep
the same as c
+ `l` - leap
YAP will execute until it meets a port for a spied predicate; this mode
keeps all computation history for debugging purposes, so it is more
expensive than standard execution. Use <tt>k</tt> or <tt>z</tt> for fast execution.
+ `k` - quasi-leap
similar to leap but faster since the computation history is
not kept; useful when leap becomes too slow.
+ `z` - zip
same as <tt>k</tt>
+ `s` - skip
YAP will continue execution without showing any messages until
returning to the current activation. Spy-points will be ignored in this
mode. Note that this command keeps all debugging history, use <tt>t</tt> for fast execution. This command is meaningless, and therefore illegal, in the fail
and exit ports.
+ `t` - fast-skip
similar to skip but faster since computation history is not
kept; useful if skip becomes slow.
+ `f [ _GoalId_]` - fail
If given no argument, forces YAP to fail the goal, skipping the fail
port and backtracking to the parent.
If <tt>f</tt> receives a goal number as
the argument, the command fails all the way to the goal. If goal _GoalId_ has completed execution, YAP fails until meeting the first active ancestor.
+ `r` [ _GoalId_] - retry
This command forces YAP to jump back call to the port. Note that any
side effects of the goal cannot be undone. This command is not available
at the call port. If <tt>f</tt> receives a goal number as the argument, the
command retries goal _GoalId_ instead. If goal _GoalId_ has
completed execution, YAP fails until meeting the first active ancestor.
+ `a` - abort
execution will be aborted, and the interpreter will return to the
top-level. YAP disactivates debug mode, but spypoints are not removed.
+ `n` - nodebug
stop debugging and continue execution. The command will not clear active
spy-points.
+ `e` - exit
leave YAP.
+ `h` - help
show the debugger commands.
+ `!` Query
execute a query. YAP will not show the result of the query.
+ `b` - break
break active execution and launch a break level. This is the same as `!break`.
+ `+` - spy this goal
start spying the active goal. The same as `! spy G` where _G_
is the active goal.
+ `-` - nospy this goal
stop spying the active goal. The same as `! nospy G` where _G_ is
the active goal.
+ `p` - print
shows the active goal using print/1
+ `d` - display
shows the active goal using display/1
+ `<Depth` - debugger write depth
sets the maximum write depth, both for composite terms and lists, that
will be used by the debugger. For more
information about `write_depth/2` ( (see Input/Output Control)).
+ `<` - full term
resets to the default of ten the debugger's maximum write depth. For
more information about `write_depth/2` ( (see Input/Output Control)).
+ `A` - alternatives
show the list of backtrack points in the current execution.
+ `g [ _N_]`
show the list of ancestors in the current debugging environment. If it
receives _N_, show the first _N_ ancestors.
The debugging information, when fast-skip `quasi-leap` is used, will
be lost.
*/
/*-----------------------------------------------------------------------------
spy

View File

@ -15,7 +15,17 @@
* *
*************************************************************************/
:- system_module( '$_depth_bound', [depth_bound_call/2], []).
/**
@defgroup DepthLimited Depth Limited Search
@ingroup YAPExtensions
YAP implements various extensions to the default Prolog search. One of
the most iseful s restricting the maximum search depth.
*/
:-
system_module( '$_depth_bound', [depth_bound_call/2], []).
%depth_bound_call(A,D) :-
%write(depth_bound_call(A,D)), nl, fail.

View File

@ -105,6 +105,14 @@
user:'$LoopError'(Error, top)).
'$exec_directive'(discontiguous(D), _, M, _, _) :-
'$discontiguous'(D,M).
/** @pred initialization
Execute the goals defined by initialization/1. Only the first answer is
considered.
*/
'$exec_directive'(initialization(D), _, M, _, _) :-
'$initialization'(M:D).
'$exec_directive'(initialization(D,OPT), _, M, _, _) :-

View File

@ -194,6 +194,16 @@
* *
*************************************************************************/
/** @defgroup YAPError Error Handling
@ingroup YAPControl
The error handler is called when there is an execution error or a
warning needs to be displayed. The handlers include a number of hooks
to allow user-control.
*/
:- system_module( '$_errors', [message_to_string/2,
print_message/2], ['$Error'/1,
'$do_error'/2]).
@ -243,9 +253,43 @@
'$process_error'(Throw, _) :-
print_message(error,error(unhandled_exception,Throw)).
/** @pred message_to_string(+ _Term_, - _String_)
Translates a message-term into a string object. Primarily intended for SWI-Prolog emulation.
*/
message_to_string(Event, Message) :-
'$messages':generate_message(Event, Message, []).
/** @pred print_message(+ _Kind_, _Term_)
The predicate print_message/2 is used to print messages, notably from
exceptions in a human-readable format. _Kind_ is one of
`informational`, `banner`, `warning`, `error`,
`help` or `silent`. A human-readable message is printed to
the stream user_error.
If the Prolog flag verbose is `silent`, messages with
_Kind_ `informational`, or `banner` are treated as
silent.@c See \cmdlineoption{-q}.
This predicate first translates the _Term_ into a list of `message
lines` (see print_message_lines/3 for details). Next it will
call the hook message_hook/3 to allow the user intercepting the
message. If message_hook/3 fails it will print the message unless
_Kind_ is silent.
If you need to report errors from your own predicates, we advise you to
stick to the existing error terms if you can; but should you need to
invent new ones, you can define corresponding error messages by
asserting clauses for `prolog:message/2`. You will need to declare
the predicate as multifile.
*/
print_message(force(_Severity), Msg) :- !,
print(user_error,Msg).
print_message(error, error(Msg,Info)) :- var(Info), !,

Some files were not shown because too many files have changed in this diff Show More