Home

YAP User`s Manual - home page

image

Contents

1. 59 GE HEEN 59 F format 2 ihre hada WEEN 46 EE 48 I EE 59 L Listing 0 sors St den EE geed 56 N nth clause 3 zi d pie hus rese rede 56 nth recorded E ag ode geen gd thease 59 number chats 2 Age de cine ui 33 Op en 4s Ai Lear d ELS EX RRRERETLIHU REI ee 41 P predicate_property 2 0c cece eee eee 57 prolog Imitialzation 80 R read emm Aere a de deed vende iw du 44 read term e e r auc BEE DENE ese 50 record 3 EE RR T robs S 58 recordarmot 34 2 ere ptu S d eR awe dn 59 recorded 8 ee E SE Se 59 RECOLdG EE 58 EEN 56 EE coc sad Cot re pP Se PERS ahem 58 mebractall Vics EE 56 Setof Side sek epe hd EE EE Bas 62 EE 72 statisties 2 AE y UR dE dake s 72 U UNKNOWN EE 31 V VETSION Ole eeh Ae RAA 80 23 2 4 Yap predicates not available in SICStus Prolog These are YAP built ins not available in SICStus Prolog A abolish table 1 i e eme eur th eee beds 149 190 ad jo array element u uninrrnrrrrnune 71 Slam Age 65 EES 62 always prompt user 0 00 sees eee ee eee 52 e TEE 109 axrag Di cues peter ed lead abe baci g awe tae ene ee 70 array element 3 eee eee eee 71 assert steil cc ree reri Fee eae eee 56 asserta statiC EE 56 assertz stat1c 1 coss pha eru ICI EIE 56 atom concab S EE A Ste ER atom Tengthi 2 26i Ee EEN cased neces 33 atomicucontat cessa ce rd ed sede Ee 33 attr umfy hook 2 i ocn sett t Heese nae es 112 EE 119 avl insert 4 EE 86 e EE 86 B b g
2. The debugger message will be shown while creeping or at spy points and it includes four or five fields Chapter 19 Debugging 157 e 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 still has alternatives to be tried If the second character is a execution is at a spy point If the third character is a gt execution has returned either from a skip a fail or a redo command e 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 e In the third field the debugger shows the active port e The fourth field is the goal The goal is written by write 1 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 1 leap YAP will continue execution until a port of a spied predicate is found
3. 182 23 2 Compatibility with the Quintus and SICStus Prolog systems EE E EE 183 23 2 1 Major Differences between YAP and SICStus Prolog 183 23 2 2 Yap predicates fully compatible with SICStus Prolog 184 23 2 3 Yap predicates not strictly compatible with SICStus Prolog I rep POTETE 188 23 2 4 Yap predicates not available in SICStus Prolog 189 23 8 Compatibility with the ISO Prolog standard 192 Appendix A Summary of Yap Predefined Operator Sass ve quce e dr hee RUE e RC eg 195 Predicate Index uuu Ee ewer awed nae 197 Concept Delega Nee hn ek yarn 205 vi YAP Prolog User s Manual Introduction 1 Introduction This document provides User information on version No value for VERSION of YAP yet another prolog The YAP Prolog System is a high performance Prolog compiler developed at LIACC Universidade do Porto YAP provides several important features e Speed YAP is widely considered one of the fastest available Prolog systems e Functionality it supports stream I O sockets modules exceptions Prolog debugger C interface dynamic code internal database DCGs saved states co routining arrays e We explicitly allow both commercial and non commercial use of YAP YAP is based on the David H D Warren s WAM Warren Abstract Machine with several optimizations for better performance YAP follows the Edinburgh tradition and was originally designed to be largely compatible wi
4. checklist Pred List Succeeds if the predicate Pred succeeds on all elements of List selectlist Pred ListIn List ut Creates ListOut of all list elements of ListIn that pass a given test convlist Pred ListIn List ut A combination of maplist and selectlist creates ListOut by applying the predicate Pred to all list elements on which Pred succeeds sumlist Pred List AccIn AccOut Calls Pred on all elements of List and collects a result in Accumulator mapargs Pred TermIn TermOut Creates TermOut by applying the predicate Pred to all arguments of TermIn sumargs Pred Term AccIn AccOut Calls the predicate Pred on all arguments of Term and collects a result in Accumulator mapnodes Pred TermIn TermOut Creates TermOut by applying the predicate Pred to all sub terms of Termin depth first and left to right order checknodes Pred Term Succeeds if the predicate Pred succeeds on all sub terms of Term depth first and left to right order sumnodes Pred Term AccIn Acc Out Calls the predicate Pred on all sub terms of Term and collect a result in Accu mulator depth first and left to right order Examples 84 YAP Prolog User s Manual given plus X Y Z Z is X Y pius if pos X Y 2 Y O Z is X Y vars X Y XIY var X vars Y Y trans TermIn TermOut compound TermIn atom TermIn TermIn plArgs TermOut qlArgs trans X X
5. 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 e if N 1 0 prompt on fail e if N 2 0 prompt on redo e if N 4 0 prompt on exit e if N 8 0 prompt on call 156 YAP Prolog User s Manual 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 spy write Stream Term If defined by the user this predicate will be used to print goals by the debugger instead of write 2 trace Switches on the debugger and starts tracing 19 2 Interacting with the debugger Debugging with YAP is similar to debugging with C Prolog Both systems include a pro cedural debugger based in the four port model In this model execution is seen at the procedure level each activation of a procedure is seen as
6. meta predicate G1 Gn Each Gi is a mode specification For example a declaration for ca11 1 and setof 3 would be of the form meta predicate call setof 7 If the argument is or an integer the argument is a call and must be expanded Otherwise the argument should not be expanded Note that the system already includes declarations for all built ins In the previous example the only argument to call 1 must be expanded resulting in the following code module example a 1 a G call example G 26 YAP Prolog User s Manual Chapter 6 Built In Predicates 27 6 Built In Predicates 6 1 Control Predicates This chapter describes the predicates for controlling the execution of Prolog programs In the description of the arguments of functors the following notation will be used e a preceding plus sign will denote an argument as an input argument it cannot be a free variable at the time of the call e a preceding minus sign will denote an output argument e an argument with no preceding symbol can be used in both ways P Q 180 Conjunction of goals and Example p X qUO SERA should be read as p X if q X and r X P Q ISO Disjunction of goals or Example p X q X r X should be read as p X if q X or r X true ISO Succeeds once fail ISO Fails always false The same as fail ISO Read as cut Cuts any choices taken in the current proced
7. P gt Q if P then Q P gt Q R if P then Q else R These two predicates could be defined respectively in Prolog as P gt Q T P D Q and P gt Q R 27 P P Q P gt Q R R if there were no cuts in P Q and R Note that the commit operator works by cutting any alternative solutions of P Note also that you can use chains of commit operators like P Q R 5S T Note that gt 2 does not affect the scope of cuts in its arguments repeat 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 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 n1 are executed repeatedly because backtracking is caught by the repeat goal The built in repeat 1 could be defined in Prolog by repeat repeat repeat Chapter 6 Built In Predicates 29 call P ISO If P is instantiated to an atom or a compound term the goal call P is executed as if the value of P was found instead of the call to ca11 1 except that any cut occurring in P only cuts alternatives in the execution of P incore P The same as call 1 call_with_args Name Ai Meta call where Name is the name of the procedure to be called and the Ai are the arguments The number of argu
8. Prints the term T to the current output stream using write 1 unless T is bound and a call to the user defined predicate portray 1 succeeds To do pretty printing of terms the user should define suitable clauses for portray 1 and use print 1 format T L Print formatted output to the current output stream The arguments in list L are output according to the string or atom T A control sequence is introduced by a w The following control sequences are available in YAP Wea Print a single tilde nva The next argument must be an atom that will be printed as if by write 7 Nei The next argument must be an integer that will be printed as a character code The number N is the number of times to print the character default 1 3 Ne 3 3 NE H 3 Nf 3 3 Ng gt gt NG The next argument must be a floating point number The float F the number N and the control code c will be passed to printf as printf s Nc F As an example format 8e 8bE 8f Ge 8G w 3 14 3 14 3 14 3 14 3 14 3 14 3 140000e 00 3 140000E 00 3 140000 3 14 3 143 14 Nd The next argument must be an integer and N is the number of digits after the decimal point If N is O no decimal points will be printed The default is N 0 format 2d d 15000 150001 150 00 15000 gt ND Identical to Nd except that commas are used to separate groups of three digits format 2D D 150000 150000 1 500 00 150
9. Seconds The mktime 1 procedure 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 Day OfTheMonth 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 7 delete_file File The delete_file 1 procedure removes file File If File is a directory remove the directory and all its subdirectories delete_file x delete_file File 0pts 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 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 file_exists File The atom File corresponds to an existing file Chapter 7 Library Predicates 99 file_exists File Permissions The atom File corresponds to an existing file wi
10. Success maplist plus 1 1 2 3 4 2 3 4 5 checklist var X Y Z selectlist 0 1 0 1 1 convlist plus if pos 1 1 0 1 2 sumlist plus 1 2 3 4 1 11 mapargs number atom s 1 2 3 s 1 2 3 sumargs vars s 1 X 2 Y Y X mapnodes trans p a p b a c q a q b a c checknodes T p X p Y X Z sumnodes vars c X p X Y q O Y Y X X another one maplist mapargs number atom c 1 8 1 2 32 cC 172 80 1 2 3 D 7 2 Association Lists 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 im plementation on top of unbalanced binary trees The current code utilises code from the red black trees library and emulates the SICStus Prolog interface 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 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 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 del_min_assoc Assoc Key Val NewAssoc Succeeds if NewAssoc is an association list obtained
11. Ae ech dg A PORE urdai 102 call x sidue 2 i dase Der ee o PLUR EARS 116 callable l EEN 82 char code 2 sies be drp td p sit bbs 34 Chal conversion ae ENEE 45 cleanup all 0 e bre EE 102 close vss ecu cde ete edlen EE 41 COMUPALC Bsc ae fte rdr cue bapti pde 35 compiled EES 19 complement 3 bie dened HS REN e eere 105 COMpPOSE EE 106 Compound Zug Re d Ee Eed 32 EE 35 create imutable 2 reri cca yees e e eee va 67 current atonal ood Eeer get bte 57 current char conversion 2 45 current iuput T ere as he Ru ente 42 G Erent EE 59 current module 1 ieri RI eR erep npa T2 Current EE 72 Current op 3 e se sans E Eeer ee A ROS 80 UE GOERENS A 42 current Dredicate 57 current predicate 2 eee 57 current stream 3 NEEN eee Rte 42 cyclic tetm L cse eret A Her 101 D atime T oreet ot m UU REA RE Rua ahs 98 db reference 1 eii ae che Gia eee Rt Ee A 32 debu ggmg 0 eet 155 del assoc 4 s sese ciere EES 84 del edges 3 5 ceo ee b hU PME ee dee 105 del max assoc A e eie e eee pem em 84 del min assoc 4 ice cain peer ERR Hermes 84 del vertices 3 0 0 02 cece eee eee 104 delete 3 ut er renee diver nee ege 87 delete fie 1 Seier k S dere 98 delete ftile 2 eo cectpi eed ood raria prb Eu 98 doraph del vertiees 107 EEN 115 directory files 2 resti ex RE RREUDE ERAS 98 discontiguous 1 directive 21 display Ali iude ette ette EUER 45 50 186 dis
12. 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 verify attributes 3 is actually called before Var is unified with Value It is up to the user to define which actions may be performed by verify attributes 3 but the procedure is expected to return in Goals a list of goals to be called after Var is unified with Value If verify attributes 3 fails the unification will fail Chapter 10 Attributed Variables 119 Notice that the verify_attributes 3 may be called even if Var has no at tributes in module Module In this case the routine should simply succeed with Goals unified with the empty list attvar Var Succeed if Var is an attributed variable 10 4 Displaying Attributes Attributes are usually presented as goals The following routines are used by built in pred icates such as call residue 2 and by the Prolog top level to display attributes 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 Module project attributes QueryVars AttrVars User defined procedure called to project the attributes in the query AttrVars given that the set of variables in the query is Query Vars 10 5 Projecting Attributes Constraint solvers must be able to project a set of
13. eene 53 socket Listen Oo socket_select 5 0 ccc eee eee 54 BOG EE 36 YAP Prolog User s Manual SOURCE EE 19 source mode 2 een 19 Splay access b sve e ERE RREFDRRRES 96 splag deleteii 0c eee 96 Splay init 2 divi ads ious enhed ages 96 Splay insert 4 i illac Erare em eases 96 Eege E dee EE AER 96 splay split EE 96 E P 155 Spy Write 2 ih dE Ae KEEN dole YS 156 EE 40 stack_dump_on_error yap_flag 2 option 77 stack_shifts stack_shifts 3 option 73 start_low_level_trace 0 151 Static array EE 70 71 static_array_location 4 70 static array properties 3 70 static array to term 3 70 Sst tistics 0 EE 72 statistics 2 ve i204 dens tous bise anes wend Ta E e DEE 42 EE E 9c RENI 42 strict iso prolog flag 2 option ES style check 1 serios CREER 21 EI E EE 34 Su blrst 29 e hsdpa ah E beach apd Geauga 88 subsumes 2 0 ccc ccc eese hann 102 subsumes chk 2 eene 102 Suffix 2 nie an i ERR TRE 88 SUI 1o 8b EES 88 sumargs 4 is bic betel sexe dme dca a eee 83 Sumbist O neparne sinepa u eae GS deque 88 Sumbyst 4 Seo sae edt a a cem db icd eked 83 sumnodes 4 ossa e DAMEN nee 83 syntax errors yap flag 2 option 77 syntax errors 1 read_term 2 option 44 GE EE 101 SyStem 1 scd pesa EES ees 64 SyStem 2 oe ksh wkd Goede bees DERE Geek od 101 system options
14. working directory CurDir NextDir Fetch the current directory at CurDir If NextDir is bound to an atom make its value the current working directory popen Command TYPE Stream Interface to the popen 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 popen 1s read X repeat getO X C C 1 put C ff X C NcygwinNhomeNN administrator The WIN32 implementation of popen 3 relies on exec 3 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 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 Chapter 7 Library Predicates 101 YAP will use COMSPEC if SHELL is undefined in this case with the option c shell Command Status Execute command Command under a new shell and unify Status with the exit for the command Yap will be in backgroun
15. 10 Attributed Variables YAP now supports the attributed variables packaged 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 uni fication 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 and Fruewirth and Holzbaur s CHR but other applications have been proposed in the literature The command use_module library atts enables the use of attributed variables The package provides the following functionality e 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 e 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 e The built in get_atts 2 can be used to check the values of an attribute associated with a variable e The unification algorithm calls the user defined predicate verify_attributes 3 before tryi
16. Create a mutex if MutexId is an atom a named mutex is created If it is a variable an anonymous mutex reference is returned There is no limit to the number of mutexes that can be created mutex destroy MutexId Destroy a mutex After this call Mutexld becomes invalid and further refer ences yield an existence error exception with mutex MutexId Goal Execute Goal while holding MutexId If Goal leaves choicepoints these are destroyed as in once 1 The mutex is unlocked regardless of whether Goal succeeds fails or raises an exception An exception thrown by Goal is re thrown after the mutex has been successfully unlocked See also mutex_create 2 Although described in the thread section this predicate is also available in the single threaded version where it behaves simply as once 1 mutex_lock MutexId Lock the mutex Prolog mutexes are recursive mutexes they can be locked multiple times by the same thread Only after unlocking it as many times as it is locked the mutex becomes available for locking by other threads If another thread has locked the mutex the calling thread is suspended until to mutex is unlocked If MutexlId is an atom and there is no current mutex with that name the mutex is created automatically using mutex_create 1 This implies named mutexes need not be declared explicitly Please note that locking and unlocking mutexes should be paired carefully Especially make sure to unlock mutexes even if the
17. EE 51 ttytab l sess e e eene 51 U undgraph del vertices 3 108 unify with oceums check been 35 unknown predicate handler 3 31 update mutable 2 00 0000005 67 use nodule A DEER 24 USE T lee Sue 25 use module 3 en Zeche ee SEAN 25 V EE 32 VARIAN Oss EE 101 verify attributes ee o eet 118 ELE 80 EES ah gedu 104 vertices edges to ugraph 3 104 W GOD EE 101 EE 116 with output to chars 2 lslssssesss 97 with output to chara sank ed 97 with output to chara di esses 97 working directory 2 0 eee e eee ee 100 Wille Ly reegt 45 KA 50 KEE 45 KA on MP 50 Write to chars 2 eicere d XR IAEA 96 wrlte to EE 96 ENEE civ utacet tet ies et es ween E Sega 46 KEE 50 Chapter 23 Compatibility with Other Prolog systems 189 23 2 3 Yap predicates not strictly compatible with SICStus Prolog These are YAP built ins that are also available in SICStus Prolog but that are not fully compatible Barm 19 IG cep mcd uc Sec e eL rd 19 A abolish 1 ep HESPERIA epe dE dus 55 abolish 2 eee Re IEEE EE pe Men RE bee 55 EE 55 EE 58 asserta I eet 55 EE 58 ass rtz WEE 55 ASSOFUZ 2 E wean EE e ub ZE 58 EE 33 B Ba ONS cs Ee ES Bett da ebd ee 62 C clause 2 eodeni eoe ach aah EE ne 56 E 56 Clo86 2 ev ubtis EEEE coker ees 41 D debug 0 7 eder ERE MELDE CIERRE 155 dynamic l 21 Date ebbe ve are ny 55 E DO UM
18. First predicates which will change during execution should be declared as dynamic by using commands like dynamic f n where f is the predicate name and n is the arity of the predicate Note that several such predicates can be declared in a single command dynamic f 2 g 1 Primitive predicates such as retract apply only to dynamic predicates Finally note that not all the C Prolog primitive predicates are implemented in YAP They can easily be detected using the unknown system predicate provided by YAP Last by default YAP enables character escapes in strings You can disable the special interpretation for the escape character by using yap flag character escapes off or by using yap flag language cprolog 23 1 2 Yap predicates fully compatible with C Prolog These are the Prolog built ins that are fully compatible in both C Prolog and YAP lt T EE HEEC COMPRE 40 5 NEE mO t E E E 35 SS anaana aaaea araa onran nna 40 Alte Soak ae le A 40 EE 36 176 gt Ee 40 EE 40 OLID as e Ui ene en he Ae el 36 ON EE 36 Eege 36 EIS LEE 19 IESSEN 19 Ny acces geed e het sd eens da eas 28 eB MN HRK 36 A abott 0 ett mE APER PURI RENE 30 atom erreira Ree E E rd EO pag 32 CA EE 32 B horno S est ee reg dn EE eg 62 brealk 0 iustos Ent BEEN dense ees 30 C Gall T 442 tuer pis tics beg tne beeen Pao t ees 29 close 1 ccu bee RIP RE atts kde IEEE 41 D EN rex see bere PUn
19. If Queue is an atom create a named queue To avoid ambiguity on thread send message 2 the name of a queue may not be in use as a thread name If Queue is unbound an anonymous queue is created and Queue is unified to its identifier thread message queue destroy Queue Destroy a message queue created with message queue create 1 It is not allows to destroy the queue of a thread Neither is it allowed to destroy a queue other threads are waiting for or for anynymous message queues may try to wait for later thread_get_message Queue Term As thread_get_message 1 operating on a given queue It is allowed to peek into another thread s message queue an operation that can be used to check whether a thread has swallowed a message sent to it Chapter 14 Threads 143 Explicit message queues are designed with the worker pool model in mind where multiple threads wait on a single queue and pick up the first goal to execute Below is a simple implementation where the workers execute arbitrary Prolog goals Note that this example provides no means to tell when all work is done This must be realised using additional synchronisation create_workers Id N 4 Create a pool with given Id and number of workers create workers Id N message queue create Id forall between 1 N thread create do work Id _ do work Id repeat thread get message Id Goal C catch Goal E print_message error E gt t
20. List1 List2 List3 Succeeds when List3 unifies with the concatenation of List and List2 The predicate can be used with any instantiation pattern even three variables 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 chdir Dir Compatibility predicate New code should use working_directory 2 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 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 nthi 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 t
21. X 32 Y 1 L 2 1 X _32 Y 2 L 2 no setof X P B ISO Similar to bagof T G L but sorting list L and keeping only one copy of each element Again assuming the same clauses as in the examples above the reply to the query Chapter 6 Built In Predicates 63 setof X a X Y L would be X 32 Y 1 L 1 2 X _32 Y 2 L 2 no 6 11 Grammar Rules Grammar rules in Prolog are both a convenient way to express definite clause grammars and an extension of the well known context free grammars A grammar rule is of the form head gt body where both head and body are sequences of one or more items linked by the standard conjunction operator Items can be e a non terminal symbol may be either a complex term or an atom a terminal symbol may be any Prolog symbol Terminals are written as Prolog lists e an empty body is written as the empty list e extra conditions may be inserted as Prolog procedure calls by being written inside curly brackets and H e the left side of a rule consists of a nonterminal and an optional list of terminals e alternatives may be stated in the right hand side of the rule by using the disjunction operator e the cut and conditional symbol gt may be inserted in the right hand side of a grammar rule Grammar related built in predicates expand term T X This predicate is used by YAP for preprocessing each top level term read whe
22. a b of arity two e In the first rule for term 0 no blank space should exist between atom and e Each term to be read by the YAP parser must end with a single dot followed by a blank in the sense mentioned in the previous paragraph When a name consisting of a single dot could be taken for the end of term marker the ambiguity should be avoided by surrounding the dot with single quotes 3 2 Prolog Tokens Prolog tokens are grouped into the following categories 3 2 1 Numbers Numbers can be further subdivided into integer and floating point numbers 3 2 1 1 Integers Integer numbers are described by the following regular expression lt integer gt lt digit gt lt single quote gt 0 xXo lt alpha_numeric_char gt where stands for optionality optional repetition one or more times lt digit gt denotes one of the characters 0 9 denotes or and lt single quote gt denotes the character The digits before the lt single quote gt character when present form the number basis that can go from 0 1 and up to 36 Letters from A to Z are used when the basis is larger than 10 Note that if no basis is specified then base 10 is assumed Note also that the last digit 2 of an integer token can not be immediately followed by one of the characters e E or Following the ISO standard YAP also accepts directives of the form Ox to represent numbers in hexadecimal base and of the f
23. constant prefixed with the and unary operators The prefix 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 depends on the module on which the built ins have been invoked Module get_atts Var 7ListOfAttributes 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 kbd prefix may be dropped The meaning of and is Attribute Unifies Attribute with a corresponding attribute associated with Var fails oth erwise Attribute Succeeds if a corresponding attribute is not associated with Var The arguments of Attribute are ignored 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 10 3 Attributed Unification The user predicate predicate verify attributes 3 is called when attempting to unify an attributed variable which might have attributes in some Module Module verify attributes Var
24. de l Sttr 2 44 a aa ea a dr 112 del edges 3 rreri eis ier are EE EEE 105 del max assoc 4 lesen 84 del min assoc 4 seen 84 del vertices 3 eee 104 delete 3 ele dert dne Heme ud eitis 87 delete filei l vene 98 delete file 2 c n 98 dgraph add edges 107 dgraph_add_vertices 3 107 dgraph complement sess 107 degraph comp ose 3 A EE Gd meus 107 dgraph del edges 3 rester iit ses 107 dgraph del vertices 107 dgraph edges 2 erior bost eere 107 dgraph neigbbore sess 107 dgraph neighbours 3 c enr 107 degraph reet eier P EX 106 dgraph symmetric closure 2 107 dgraph top sort 2 Le b E Re geed EH 107 dgraph transitive closure 2 107 dgraph transpose 2 sees kesis 107 dgraph vertices 2 o bere hr gs 107 dif 246 EE ERR 115 directory prolog_load_context 2 option 80 directory files 2 EE 98 discontiguous 1 directive 21 discontiguous warnings yap flag 2 option rcr 74 77 diSplay 1 dies seg peso SEAN 45 50 display 2 os 2 gcd e UR ERG Wu GR RU CS gave 50 do not compile expressions 0 20 dollar as lower case yap flag 2 option 74 double quotes yap flag 2 option 74 Ke EE 55 dynamic Dredicate sss seeeees 55 E edges 2 csse par tame PRA E Re Edd 104 enpty assoc izgoc sicizescde RERGUGG Rd 85 empty he ap 1 ege 86 empty EE 91 ensure Voaded EE
25. is op 500 yfx NV NP 29 7 196 op 500 fx op 400 yfx 3 5 952 2 f Weed a ATN op 300 xfx mod op 200 xfy op 50 xfx same YAP Prolog User s Manual Predicate Index Predicate Index 197 ADOLDPSH PEDER SEE Gah hos eg Eeer dE 55 abolish table 1 dE Rer RETI 149 abort O i cud ug Y Peu Y eae a udis 30 absolute file n me 2 cee ues 42 add edges 3 veo iii eri deeb 105 add to array elemnenr i ss St add to Dest ct dae ene ere de d 86 add to EE 20 add to path 2 gt brodne erir ET REIS 21 add vertices 3 eee 104 alatmn 3 anna phim a uut Rui ee 65 amp Ll 3 2 Rar 3 Ee err ed e 62 alvae prompt user reie tiisin iaiiia ii 52 append 3 Ech oot susan 87 109 SE EA iere 34 argv yap_flag 2 option T3 array Dieter yp pee a RC RE Qtr hd epe 70 array element EE 71 asSsert 1 icenuese d Rra a Ni NED d Pen 55 asSSert 2 u cuc se duo Da ce Bee daub Sakae 58 assert static 1l cene 56 asserta 1 2 5 2 ecd Pees Malone tng a0 55 asserta 2 WEE 58 asserta Static 1 ae poche ees See UN anes 56 assertz 1 oo hein etd hohe E 55 assertz 2 orei eet E OEE E E a 58 a ssertz static I ereere aeree e eet 56 assoc boi Ist E 84 at end of Stream Or ENEE 42 at nd of Strean EE 42 CHE 32 atom Chars 2 ees aes eR SA sah 33 atom codes 2 es banens erne bed bs 33 atom concat ol pid e rE SEEE D 33 ato
26. lt Constraint gt Constraints disjunction NN lt Constraint gt gt lt Expression gt lt lt Expression gt less than lt Expression gt gt lt Expression gt greater than lt Expression gt lt lt Expression gt less or equal lt lt Expression gt lt Expression gt less or equal lt Expression gt gt lt Expression gt greater or equal lt Expression gt lt Expression gt not equal lt Expression gt lt Expression gt equal lt Expression gt lt Expression gt equal lt Expression gt gt lt Variable gt W Prolog variable lt Number gt Prolog number float integer lt Expression gt unary plus lt Expression gt unary minus lt Expression gt lt Expression gt addition lt Expression gt lt Expression gt substraction lt Expression gt lt Expression gt multiplication lt Expression gt lt Expression gt division abs lt Expression gt absolute value sin lt Expression gt sine cos lt Expression gt W cosine W tan lt Expression gt W tangent exp lt Expression gt exponent pow lt Expression gt exponent lt Expression gt Expression exponent W min lt Expression gt lt Expression gt minimum Chapter 11 Constraint Logic Programming over Reals 125 max lt Expr
27. rules gt rule rules rules gt rule gt name actual_rule pragma atom name gt atom atom name gt actual_rule gt simplification_rule actual_rule gt propagation_rule actual_rule gt simpagation_rule simplification rule gt constraints atom lt gt guard body 128 YAP Prolog User s Manual propagation_rule gt constraints atom gt guard body simpagation rule gt constraints atom constraints atom lt gt j guard body constraints gt constraint constraint_id constraints gt constraint atom constraints constraint gt compound_term constraint_id gt constraint_id gt atom variable guard gt guard goal atom body gt goal pragma gt pragma gt atom pragma actual_pragmas actual_pragmas gt actual_pragma actual_pragmas gt actual_pragma atom actual_pragmas actual pragma gt atom passive variable atom Additional syntax related terminology e head the constraints in an actual_rule before the arrow either lt gt or gt 12 2 2 Semantics In this subsection the operational semantics of CHR in Prolog are presented informally They do not differ essentially from other CHR systems When a constraint is called it is considered an active c
28. 19 GENEE 64 99 GE 59 Predicate Index eraseall 1 22 e eh nid ER A deg erased 1 cineildbuesegd deis uu RE hi aaa Se clo HE exists d sien cise ates Bee Le i uei expand 6xprs 2 os cago epa dL LERREPRPR RI expand term 2 ii4i E bed hace eae meses d F PAW EE Eege hed dar ated M s fast yap_flag 2 option file prolog_load_context 2 option file exists 1 ek eee eee EN EN file exists 2 EE il _prop rty 2 Ae NNN hie beaten gee es file search path 2 2o sce EISEN EEN fileerrors yap_flag 2 option 11 6Grrors d EE findall 3 EES SE EM EE flatten 2 ee EE E POAT gen rege float_format yap_flag 2 option flush output 0 ois wicnacenses os Peta ees flush GEREEST EE EE EEN format E GEN format to chars 4 e EEN Brei Snes pma pnm freeze 9 62 oho dd ble eta eges edi gie EE f nctor 3 EE G garbage collect O 22224 er p e garbage_collect_atoms 0 garbage collection statistics 2 option gc yap_flag 2 option rJ m gc margin yap flag 2 option gc trace yap flag 2 option gen ass c 3 ioca bete d veri PEERS BOC Tics Eege ere usa ttu etd EE EE EE EE E EE EE get EES ee act bb e messed Pe Saad get byte 1 i spese eere eee lage g t byte 2 EEN rre inu LER RU RAW get char 1l 2st RA lak p DERI deret eque ste get char 2 sede e pP ERR wad SO DEE 199 get co de 2 s
29. 2 EE 5i permutation 21 iior imag ede Rd pease 88 phrase 2 vu bi eei sep AUR RE d pd 64 phrase 3 ied oe Ii veda er d eps 64 p poPQ M eebe 100 ppl Rm 100 portray clause 1 c 0 1 ennerien edi 57 portray EE EE 57 predicate property 2 sss ee sess 57 primitive l EE 32 PLING EE 46 PYANG 2 E deg dree bel e hades 50 profile Gate aces Perec d dee 68 profiled reser cece eee eee eee 68 profiling yap_flag 2 option 76 program statistics 2 option 73 project_attributes 2 00 119 prolog file riame 2 eee codes E ees 22 prolog flag 3 4 i e E ere v E Y EET 80 prolog initialization 1 80 prolog load context 2 suus 80 PLOMPE 2 c erbe ever EPIRI AERIS 80 public 1 directive 2 2b yg 22 DUt 1 Agrar acess 48 o EE 50 ONE 85 p t attr 3 EE 112 put attrs 2 3 2 2 REES E giereg 112 ONE EEN 118 put byte l zx eos e rising Au TET RES 48 put byte 2 iesse p d EIRPNE e e ER RR d 50 put char 1 i weed sb arsen i Gans a Fa be 48 201 Pub Char EE 50 p t code sic couette gk eeu PEE Pa 49 putocode 2 EE 50 Put Label EEN 103 PUbCHV renr nieue PaA ORE E dae he 64 Q queue EE EE E 91 R random 1 ile e eee ao IX de Gea en rid 91 PANdOM EE 91 Pandseg 3 EE 91 E EE 92 EE 90 Tanstart 0 EE 90 ranstart 1 EE 90 ranu nit 2 EE 90 rb applily 4 e peeks were E eee EE 93 rb clone 3 L0Be Bi v e Y ebbe MITMRE qun 93 fb
30. 3 2 Signalling Thread 143 14 3 8 Threads and Dynamic Predicates 144 14 4 Thread Synchronisation 144 15 Parallelism s s pete n9 TE Es 147 l6 Tabing aere vw ene EE 149 17 Tracing at Low Level ow 151 18 Profiling the Abstract Machine 153 19 JDebupgpingi ssceeskx 9x REX RR Y 155 19 1 Debugging Predicates lssseeesseee cee eee ee 155 19 2 Interacting with the delbugger 0 eee 156 20 Indexing GE e EE E e ds 159 21 C Language interface to YAP 161 21 1 Tersi AE Se hed inden TR RA ned head eee 162 21 2 D tee EE 165 PME Vina a eegene ECH 165 21 4 Memory Allocaton 0 0 c cece eee eee eens 165 21 5 Controlling Yap Streams from 166 21 6 From C back to Prolog bare eee cece teen eee 166 21 7 Writing predicates me 166 21 8 Loading Object les 169 21 9 Saving and Restoring 0 00 c eee eee eee ees 169 21 10 Changes to the C Interface in Van 169 22 Using YAP as a Library 171 23 Compatibility with Other Prolog systems 175 23 1 Compatibility with the C Prolog interpreter 175 23 1 4 Major Differences between YAP and C Prolog 175 23 1 2 Yap predicates fully compatible with C Prolog 175 23 1 3 Yap predicates not strictly compatible with C Prolog 177 23 1 4 Yap predicates not available in C Prolog 177 23 1 5 Yap predicates not available in C Prolog
31. 4 2 0 Escape sequences can be disable by using yap flag character escapes off 3 2 3 Atoms Atoms are defined by one of the following rules atom solo character atom lower case letter name character atom symbol character atom single quote single quote atom gt atom quoted characters atom quoted characters gt 77 atom quoted characters atom quoted characters gt atom sequence string quoted characters atom quoted characters gt character string quoted characters where lt solo character gt denotes one of Is lt symbol character gt denotes one of amp ex x 1 i lt 70N 7 lt lower case letter gt denotes one of a Z lt name character gt denotes one of E ME EE 0 9 lt single quote gt denotes and string_character denotes any character except the double quote and escape char acters Note that escape sequences in strings and atoms follow the same rules Examples a al2x a gt 012 Version 4 2 0 of YAP removed the previous limit of 256 characters on an atom Size of an atom is now only limited by the space available in the system 3 2 4 Variables Variables are described by lt variable starter gt lt variable character gt where Chapter 3 Syntax 17 lt variable starter gt denotes one of s AL eZ lt variable character gt denotes one of S8 E Ass 2Z If a variable is referred only once in a term it needs not to be na
32. 7 15 Utilities On Terms 00 000 ccc cece s 101 7 16 Call Cleanup EE 102 7 17 Calls With Timeout 0 00 00 ccc ect eee nes 102 7 18 Updatable Binary rees 103 1 19 Unweighted Graphs 22a huia aaa a sand as 103 7 20 Directed Graphs 0 eee ce eee nh 106 7 21 Undireeted Graphs 44 d daret Eh peer e 108 SWI Prolog Emulation 109 8 1 Invoking Predicates on all Members of a List 110 8 2 Foral cuiii view ep pru e edad ad arae dee s 110 8 3 hProlog and SWI Prolog Attributed Variables 110 8 3 1 Special Purpose SWI Predicates for Attributes 112 8 4 SWI Global variable 112 8 4 1 Compatibility of SWI Prolog Global Variables 114 Extensions to Prolog rot 9n 115 9 1 Rational rees 115 9 2 e E siue o4 aet ded Make PRU Rb oue EA dra ere dedos 115 10 Attributed Variables 117 10 1 Attribute Declarations 00 00 c cece eee tenes 117 10 2 Attribute Manipulation 000 ee eee eee ee eee 118 10 3 Attributed Unification 0 cece eee eee 118 10 4 Displaying Attnbutes eee eee ee 119 10 5 Projecting Attributes 0 0 cece eee eee ee 119 10 6 Attribute Examples rastas snis 0 00 cece cece eee eee eee 119 11 Constraint Logic Programming over Reals eT Tee eee Cee EE Tee oC eee See TT ee ee 123 11 1 Solver Predicates du ead ea Fee oed ea ada ened etd ee 123 11 2 Syntax of the predicate argum
33. 93 TO A EE 93 Eon ig EE name nee eae men Ee 93 rb new l ia eve eee ech hey pcd a Mees es 92 e m 93 rb partial map 4 vic en ier de t oes 93 EEN 93 EE 93 rb update 4 ces nies ahaa eed bang EE 93 CD VISI D PE RER aca sues patie nek aed EEN dada 93 KECONSUIL AER 19 Ela seg Ze n getrei 59 recorda 8b 8 EE 58 recordaifnot 3 EE 60 recordz t EE 58 recordzifnobt 3 EE 60 Yegexp 3 EE 94 EE 94 remove from path 1 ssessssseeeesee 21 renam 2 ize DP e Ntra d 64 reset op Counters crarianessskerisses 153 resize static array 3 cesse cabs ned ede TL S SAVE d caso ect dtan rre nian ae dese dels wees 22 EE 22 selectI8t 8 oa arena genie ERERIN E Rn 83 set prolog Mag 2 us EN err EO 80 8et value 2 eins esee hep RIO PR RE kend ne 60 setarg 3n wi hares rd EE ORO RE 67 nop PER 109 n WENN ME 64 show op counters 1 rere rte 153 show op by eroup eene 153 Show table nf ester e deet 149 EE EE 19 TEE 19 SplaysaGCess 5 x i ectetuer bap 96 splay delete 4 age ERREUR 96 Splay MHS o i eiveodeerUrdao dd derer oad ees 96 splay insert 4 ra s den Ree EIER PEE 96 Splay AEN ils etch n eee E PERIERE Ra 96 splay split ace nest nel epee E ELO PEE 96 Spy Wwrlte 2 css eer ri Dre x daw PROS 156 srandom 1 essi Rex parare pa AIR SE 40 192 start low level Grace t 151 Static Array Quc iienegev week e eid elg 70 71 static array Jocation d nn ieiero ni 70 static array properties 3
34. Compatibility with the Quintus and SICStus Prolog systems The Quintus Prolog system was the first Prolog compiler to use Warren s Abstract Machine This system was very influential in the Prolog community Quintus Prolog implemented compilation into an abstract machine code which was then emulated Quintus Prolog also included several new built ins an extensive library and in later releases a garbage collector The SICStus Prolog system developed at SICS Swedish Institute of Computer Science is an emulator based Prolog system largely compatible with Quintus Prolog SICStus Prolog has evolved through several versions The current version includes several extensions such as an object implementation co routining and constraints Recent work in YAP has been influenced by work in Quintus and SICStus Prolog Wher ever possible we have tried to make YAP compatible with recent versions of these systems and specifically of SICStus Prolog You should use yap flag language sicstus for maximum compatibility with SICStus Prolog 23 2 1 Major Differences between YAP and SICStus Prolog Both YAP and SICStus Prolog obey the Edinburgh Syntax and are based on the WAM Even so there are quite a few important differences e Differently from SICStus Prolog YAP does not have a notion of interpreted code All code in YAP is compiled e YAP does not support an intermediate byte code representation so the fcompile 1 and load 1 built ins are not av
35. 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 120 module domain domain 2 use module library atts use module library ordsets ord ord intersection 3 intersect 2 list to ord set 2 1 attribute dom 1 verify attributes Var Other Goals get 3 js verify attributes _ atts Var dom Da var Other gt C get atts ther dom Db gt ord intersection Da Db Dc Dc El Els Els gt ax 23 Goals Other El Goals put atts Other dom Dc Goals put atts Other dom Da Goals ord intersect Other Da attribute goal Var domain Var Dom 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 Els gt X El put_atts Fresh dom Set X Fresh YAP Prolog User s Manual are we involved must be attributed then has a domain at least one element exactly one element implied binding rescue intersection rescue the domain value in domain unification triggered because of attributes in other modules interpretation as goal at least one element exactly one element im
36. EE E Rr RU 35 consult T iere pete he RU UNE MEE aedes 19 Current atom lerese ranea nane a e 8 57 current Dredicate e ccsirccirririreiericreras 57 D dbzreference ls ccccthincnapeadh e ede m s 32 debug 0 ios obe Eege ss saga eed Siu RUN 155 debuggimg 0 ieee dere re oe ae tebe each 155 display Hl iis erdcebe ree Pond ete eee HERES 45 E erase T vus Lr s US Dd eee eens 59 erased i de dE dee Ad 59 exists T ut eens id dE dE cre OPERE YS 51 expatid expra 2 eh E dE ber we eda dus 20 expand term 2 eed oan eve HERE e REF E 63 YAP Prolog User s Manual F EE 27 fileertors O s d e ERR be eet ae 52 findall 8 et keenest eotawpeeeres ERPS 62 functor 9 deeg eidami err denser PE 34 G A NEE 49 ODOM EE 49 H halt A NEE 30 I EE 59 teser Se oie vba wath ee 32 K P tees eessp sateen teow e 36 L leash Vidal bia deta SSG SE SENERE 155 Lengthy EE 36 N Dame deg EE EEN 32 EE 49 nodebug 0 consi enero aaa wed cele cube 155 nofileerrors 0 Lesser men PER l 51 E D ekfevc ir iren bI aE E ORE 32 EE 155 not EE 28 number 1 arie Rebus gege RECORDAR 32 O ei EEN 80 P PER aa PD 32 OEM ss oe Sek de deka otk a sae eh daca Siac te 46 Drompl 2 sange reed ede e EY Reds 80 pub d oko oio eher dote iR ERE ieee ut feq 48 R ready NEE 44 reconsult EE 19 recorda 9 EE 58 Chapter 23 Compatibility with Other Prolog systems 177 Feeler Bice essed vate Eer EE Ass A i 59 ETS 58 EE 64 Tepeat Ocad noceat SEEDEDE
37. EEN 103 tree Lo Llist 2 ml e ea EIL 103 ni y PP 27 ttyget l c Ee e a AE ak 51 LEE 51 EENS teg tenga Eer 51 CtYPUE Us eet EES AE 51 ttyskip io eee ses Sass e Me Peele sens 51 EE 51 typein_module yap_flag 2 option 78 U undgraph add edges nrnna 108 undgraph add vertices 3 108 undgraph complement 2 s 108 undgraph del edges 108 undgraph del vertices 3 108 undgraph edges rieenireor upk aai es 108 undgraph neigbbore sess 108 undgraph_neighbours 3 0 108 undgraph new los ici See A eR ERG 108 undgraph vertices lesse 108 unhide 17 dree EE ee ite E 20 unify with occurs check 2 35 MTU EEN 64 unknown yap_flag 2 option 78 MTUKNO EE 31 unknown_predicate_handler 3 31 update array 3 i mee RR Periit ra upd te m table 2 osos Rr EEN 67 update semantics yap_flag 2 option 78 use_module 1 ce ae ee eee eee 24 use module n rennan 25 use module 25 203 user error yap flag 2 option 78 user input yap_flag 2 option T9 user output yap_flag 2 option 79 V cis MR Ale xa alates dab be Sake 32 variable in term eee 102 variable names 1 read term 2 option 44 variables 1 read term 2 option 44 Variant 2 EEN 101 verify attrib tes 3 li eye REDI Obr 118 version yap flag 2 option 79 W
38. Equiv alent to first calling current prolog flag 2 with the second argument Old Value unbound and then calling set_prolog_flag 2 with the third argument New Value set prolog flag Flag Value ISO Set the value for YAP Prolog flag Flag Equivalent to calling yap f1ag 2 with both arguments bound op P T A ISO Defines the operator A or the list of operators A with type T which must be one of xfx xfy yfx xf yf fx or fy and precedence P see appendix iv for a list of predefined operators Note that if there is a preexisting operator with the same name and type this operator will be discarded Also 7 7 may not be defined as an operator and it is not allowed to have the same for an infix and a postfix operator current op P T F ISO Defines the relation P is a currently defined operator of type T and precedence P prompt A B Changes YAP input prompt from A to B initialization Execute the goals defined by initialization 1 Only the first answer is consid ered prolog_initialization G Add a goal to be executed on system initialization This is compatible with SICStus Prolog s initialization 1 version Write YAP s boot message version Message Add a message to be written when yap boots or after aborting It is not possible to remove messages prolog load context Key Value Obtain information on what is going on in the compilation process The fol lowing keys are available directory Ful
39. Gee 87 MOT PC 3 5 ele EE 89 meta predicate 1 directive 25 E E EE 85 min integer yap_flag 2 option 76 Din l18t429 Sy SR re EE 89 Min Of _h ap 3 Ae seer eR DRE 87 min of _h ap 5 NEEN EIER a EEN EE 87 Hktemp 2 pi elie edie ee eee 100 kt ime EE 98 module prolog_load_context 2 option 81 module71 2212 524 sedute uh be n d tee 24 module 2 directive 24 YAP Prolog User s Manual module 3 directive 24 multifile 1 directive 21 mutex create 1 cese eee 145 mutex destroy We sci sissies deeper edtes ick ete aes 145 mutex lock 1 2 AE E AER ASA 145 mutex statistics 0 eee 141 mutex trylock l is eem ade 145 mutex unlock 1 esee eee 145 mutex unlock all 0 sese 146 N n of integer keys in bb yap flag 2 option r Ree ah dean a 76 n_of_integer_keys_in_db yap_flag 2 option abe A cal AEE Ee deeg 76 HAME EE 92 nb curreut 2 1 255 p e IREPURD UNE 113 nb delete i1 ug E 21206 R21 0v BOSE 114 nb getval 2 ve n e eror br eee ee dees 113 nb osetval 2 lacs e HUP ERA 113 heighborB 3 eosin es eater es ded re e e REFS 105 neighbours J ico6eb ble Ry e PP een 105 e EE 49 EE 51 no so urce Q0 EE 20 no style check 1 sess eeeee ese 21 NOGDEDUB Ee ee Sege SE 155 nofaileerrors 0 EE 51 nori C 30 nonvar 1l ii52
40. If more than one thread is waiting for messages on the given queue and at least one of these is waiting with a partially instantiated Term the waiting threads are all sent a wakeup signal starting a rush for the available messages in the queue This behaviour can seriously harm performance with many threads waiting on the same queue as all but the winner perform a useless scan of the queue If there is only one waiting thread or all waiting threads wait with an unbound variable an arbitrary thread is restarted to scan the queue thread get message Term Examines the thread message queue and if necessary blocks execution until a term that unifies to Term arrives in the queue After a term from the queue has been unified unified to Term the term is deleted from the queue and this predicate returns Please note that not unifying messages remain in the queue After the follow ing has been executed thread 1 has the term gnu in its queue and continues execution using A is gnat lt thread 1 gt thread_get_message a A lt thread 2 gt thread_send_message b gnu thread_send_message a gnat See also thread_peek_message 1 thread peek message Term Examines the thread message queue and compares the queued terms with Term until one unifies or the end of the queue has been reached In the first case the call succeeds possibly instantiating Term If no term from the queue unifies this call fails thread message queue create Queue
41. Manual H bat Oee ee dunes LA eS E 30 EE 30 head quedue 24 cte RE rer 91 Neap size 2i iciiisebidig EE deed E 86 heap to list 2 eege EEN 86 host Jd WEE 99 host mame 2 asec edema state Pen A 99 I PTT 29 LEE 29 initialization O EE dere cere seen ered 80 be ger 1s SEENEN 32 EE 40 EE 85 IS ep ecce SE Crescente ie 87 is mutable EE 67 J Jom queue 3 ee ited ba Y des 91 jump_queuve 3 oirrc eee eee eee 91 K EE 36 cil eee te Ore eee ee eee SEEREN 100 L E EE 87 leash Re SE SEES ROS ELSE aaa Edda 155 length 2 eege tere Sege Se aces 36 length queue 2 i ches dE de 91 list join queue 3 NE dreisi 91 list jump queue 3 ssseseeeeeeees 91 Iist to assoc 2 eese tre dee ER 85 list to Tieap 2 stet see epi een 86 list to ord set 2 ssi sec bn PIE RES 89 list to queue 2 5 ore ewe bees aude eee AER 91 list to iree 2 Poaceae hens RP waned ey 103 listing Tas Moog cps eege 56 M make drectore 0 2 e eee eee 99 make queue EE 91 GEET 85 WAP2ass0C 3 EE 85 WMAPAtree EE 103 MAX ASSOCII EE 85 MAK et AE d RER Ze 89 iui EE 87 xjemberchk 2 cs dietesctirierte e ede eee 87 IUuerge d EEN 89 Chapter 23 Compatibility with Other Prolog systems 187 meta predicate 1 directive 25 UUM ASSOC 3s eines eerte er ag ated oS a Re 85 imu l8t 2 Neger pLICRRE PRIX suns 89 nu of heap 3 ise d rer b been 87 imu ofheap b cepe SE 87 nt EE 100 module ls siete iat Ze
42. 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 T L 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 X Y ISO Tries to unify terms X and Y X V Y IS0 Succeeds if terms X and Y are not unifiable unify with occurs check T1 T2 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 unify with occurs check a X b 2 a X A B will succeed with the bindings A b and Z B On the other hand unify with occurs check a X b Z2 a X A 25 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 copy term TI TF ISO Term TF is a variant of the original term TI such that for each v
43. Possible values for this option are on to enable the checks and off to disable the checks 130 optimize debug mode YAP Prolog User s Manual This is an experimental option controlling the degree of optimization Possible values are full to enable all available optimizations and off default to disable all optimizations The default is derived from the SWI Prolog flag optimise where true is mapped to full Therefore the commandline option Q provides full CHR optimization If optimization is enabled debugging should be disabled This options enables or disables the possibility to debug the CHR code Possible values are on default and off See debugging for more details on debugging The default is derived from the prolog flag generate_debug_info which is true by default See nodebug If debugging is enabled optimization should be disabled This option specifies the mode for a particular constraint The value is a term with functor and arity equal to that of a constraint The arguments can be one of or The latter is the default The meaning is the following The corresponding argument of every occurrence of the constraint is always unbound The corresponding argument of every occurrence of the constraint is always ground The corresponding argument of every occurrence of the constraint can have any instantiation which may change over time This is the default value The declarat
44. Py ene ok ganas 28 S ER 22 TS E 44 Seel sis rr A Aa dE ec EA 44 seen fo sg cert EE 44 Sebof et Resen ESSENS SES SSD ee 62 M Seege 64 e EE 49 SOU Drs se ca hae as peal errs ae a ad ld Gus secede 36 SPV laa EUR 155 Statistics Oi is oer e aoe beads EIAS 72 System T s is See node eed a talon nolo cee eae ease 64 T Eed Eege 49 U l EE 43 telling l Aaf d ise AE Ee Bete ped 43 term espansion sees 63 EE 44 Eet nm 27 V KC os ssec are edad edebat due adatta 32 Wille le seks nena ae ete eee RE Ped ubt 45 Eeer iere IM RR ERE DP E 46 23 1 3 Yap predicates not strictly compatible with C Prolog These are YAP built ins that are also available in C Prolog but that are not fully compat ible A abolish 1 nes perone REEL ERES 55 abolish 25 sido d eege e ME ERE EI 55 EE EE 55 EE 58 asserta 1 i seek tete he CREER CER eR 55 c dr p P T T 58 ASSOLE Wiech Seeder 55 EE EE 58 C el EE 56 lageren ie ice heer PROPRES 56 I rp T 40 L Dette sci hleine bein AER EE ERRS 56 listig T ictu EE eee ete 56 N nth clause 9 ise sscoce epp EDU Ru pad ep mae 56 R EE 58 23 1 4 Yap predicates not available in C Prolog These are YAP built ins not available in C Prolog EE EEN 28 E PME LU II T EIE 35 NS PETI TT 35 A abolish table 1 i leet ey pended eed 149 absolute file name 0 cee eee eee 42 addedges 3 cropp eira oo e danas ees 105 add to array element A lssss
45. REREN es eR RE der p 91 jump SUSAN 91 200 K key statistics 3 cio ver rre bere seers 59 key statistics 4 coocoos SEENEN d 59 EE 36 e DER EE 100 L language yap_flag 2 option 75 MES Dia cos ty otek aoe Sees eh ace cee re diag ce Spee oa ao 87 DOASH esee dee Mad End a 155 VON Gth 2 ears arki debe had bbe e 36 length queue 2 EE REENEN 91 library_directory 1 0 21 22 list concat 2 ie ge EE SA 87 Tist Join Ee 2 Cheuk Ra RT edt aes 91 list jump oueue peiciiiresre ruio teias 91 list to a 5806 2 2 524 dO 4 tds 85 list to h ap 2 6l EE SG ee 86 list to ord set 2 2 2 2nbb IER wp eS 89 list to queue 2 iscRis DER RR Red sls 91 list to rbtrea 9 254 dp deo 93 list EE 103 listing 0 EE 56 Tiokinp d ci cesse cie M e dees SE DERE 56 local stack statistics 2 option 73 M Make directory EE 99 make queue 1 a dE orcii r REPRE PEERS 91 nap ss66 2 o neret eR enne 85 MAP ASSOC 3 x pede un PEL er PIE 85 map trfee 3 ii ppp p DOR Ree E 103 mapargs 3 id E Cave eed RR ordres 83 mnaplist 2 542525 9 0 daw ae wire need eaten sans 110 MAP TES ENS scl sed et esheets Sgr 83 110 naplist 4 eeen 9 M DR EE 110 mnapnodes 3 EE 83 max arity yap flag 2 option 76 Max assoc S EE 85 max integer yap_flag 2 option 76 mar TPS EE 89 max tagged integer yap_flag 2 option 76 MOMBOE 2 EE 87 memberchk 2 rosie orare EEr ERIRE REEE
46. YAP MkIntTerm n 1 return TRUE Note that again the macro YAP_PRESERVED_DATA is used at the beginning of the function to access the data preserved from the previous solution Then it checks if the last solution was found and in that case exits with YAP_cut_succeed in order to cut any further back tracking If this is not the last solution then we save the value for the next solution in the data structure and exit normally with 1 denoting success Note also that in any of the two Chapter 21 C Language interface to YAP 169 cases we use the function YAP_unify to bind the argument of the call to the value saved in ni00_state gt next_solution Note also that the only correct way to signal failure in a backtrackable predicate is to use the YAP_cut_fail macro Backtrackable predicates should be declared to YAP in a way similar to what happened with deterministic ones but using instead a call to void YAP_UserBackCPredicate char name int init int cont unsigned long int arity unsigned int sizeof where name is a string with the name of the predicate init and cont are the C functions used to start and continue the execution of the predicate arity is the predicate arity and sizeof is the size of the data to be preserved in the stack In this example we would have something like void init_n100 void YAP UserBackCPredicate ni100 start n100 continue n100 1 1 21 8 Loading Object Files The primitive pre
47. YAP usually boots from a saved state The saved state will use the default installation directory to search for the YAP binary unless you define the environment variable YAPBINDIR e YAP always tries to find saved states from the current directory first If it cannot it will use the environment variable YAPLIBDIR if defined or search the default library directory e YAP will try to find library files from the YAPSHAREDIR library directory 2 2 Running Prolog Files YAP can also be used to run Prolog files as scripts at least in Unix like environments A simple example is shown next S usr local bin yap L Hello World script file using Yap put a dot because of syntax errors write Hello World nl The characters specify that the script should call the binary file Yap Notice that many systems will require the complete path to the Yap binary The L flag indicates that YAP should consult the current file when booting and then halt The remaining arguments are then passed to YAP Note that YAP will skip the first lines if they start with the comment sign for Unix s shell YAP will consult the file and execute any commands A slightly more sophisticated example is S usr bin yap L Hello World script file using Yap 4 initialization main main write Hello World nl 2 The initialization directive tells Yap to execute the goal main after consultin
48. a free variable otherwise fails atom T ISO Succeeds if and only if T is currently instantiated to an atom atomic T ISO Checks whether T is an atomic symbol atom or number compound T ISO Checks whether T is a compound term db_reference T Checks whether T is a database reference float T ISO Checks whether T is a floating point number integer T ISO Succeeds if and only if T is currently instantiated to an integer nonvar T ISO The opposite of var T number T ISO Checks whether T is an integer or a float primitive T Checks whether T is an atomic term or a database reference simple T Checks whether T is unbound an atom or a number callable T Checks whether T is a callable term that is an atom or a compound term 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 name yap L will return L 121 97 112 and Chapter 6 Built In Predicates 33 name 3 L will return L 51 atom_chars A L 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 ASCII codes for the characters of the external representation
49. all solutions to the previous query e YAP Bool YAP GoalHasException YAP Term tp Check if the last goal generated an exception and if so copy it to the space pointed to by tp e void YAP ClearExceptions void Reset any exceptions left over by the system e void YAP Write YAP Term t void int PutC int flags Write a Term t using the function PutC to output characters The term is written according to a mask of the following flags in the flag argument YAP WRITE QUOTED YAP WRITE HANDLE VARS and YAP WRITE IGNORE OPS e void YAP WriteBuffer YAP Term t char buff unsigned int size int flags Write a YAP Term t to buffer buff with size size The term is written according to a mask of the following flags in the flag argument YAP WRITE QUOTED YAP WRITE HANDLE VARS and YAP WRITE IGNORE OPS e void YAP InitConsult int mode char filename Enter consult mode on file filename This mode maintains a few data structures internally for instance to know whether a predicate before or not It is still possible to execute goals in consult mode If mode is TRUE the file will be reconsulted otherwise just consulted In practice this function is most useful for bootstrapping Prolog as otherwise one may call the Prolog predicate compile 1 or consult 1 to do compilation 174 YAP Prolog User s Manual Note that it is up to the user to open the file filename The YAP_InitConsult function only uses the file name for internal book
50. and write to a memory buffer as if it was a file The memory buffer is built from or converted to a string of character codes by the routines in library Therefore if one wants to read from a string the string must be fully instantiated before the library built in opens the string for reading These commands are available through the use_module library charsio command 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 Form Args ResultO Result 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 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 ResultO Result Execute the built in procedure write 1 with argument Term outputting the result to the difference list of character codes Result Result0 Chapter 7 Library Predicates 97 atom_to_chars Atom Result Convert the atom Atom to the string of character codes Result atom_to_chars Atom ResultO Result Convert the atom Atom to the difference list of character codes Result Result0 number to chars Number Result Convert the number Number to the string of character codes Result number to chars Num
51. base of the natural logarithms inf Infinity according to the IEEE Floating Point standard Note that evaluating this term will generate a domain error in the iso language mode nan Not a number according to the IEEE Floating Point standard Note that eval uating this term will generate a domain error in the iso language mode cputime CPU time in seconds since YAP was invoked heapused Heap space used in bytes local Local stack in use in bytes global Global stack in use in bytes random A random floating point number between 0 and 1 40 YAP Prolog User s Manual The primitive YAP predicates involving arithmetic expressions are X is Y 2 This predicate succeeds iff the result of evaluating the expression Y unifies with X This is the predicate normally used to perform evaluation of arithmetic expressions X is 2 3 4 succeeds with X 14 X lt Y ISO The value of the expression X is less than the value of expression Y X lt Y ISO The value of the expression X is less than or equal to the value of expression Y X gt Y ISO The value of the expression X is greater than the value of expression Y X gt Y ISO The value of the expression X is greater than or equal to the value of expression Y X Y ISO The value of the expression X is equal to the value of expression Y X Y ISO The value of the expression X is different from the value of expression Y srandom X Use the argument X
52. can use array references instead of extra calls to arg 3 As an example g Y Z I J XU is Y J Z 1 should give the same results as G X Y Z I J rin 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 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 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 static array location Name Ptr Give the location for a static array with name Name 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 to term Name Term Convert a static array with na
53. ch t code 2 tee Scheer de E Eroii 34 Char vonversion sees eee 45 chdi 1 sedere pee Eed tener 109 checklist 2 A6 go tedden ben ERU E 83 Checkn0des 3 0 ned EEN bebe ee ed 83 cleanup all 0 ke Rete EE 102 GlOSC 2 41 close static aal 71 Compile WEEN 19 compile 1 directive 0 00 19 compile expressions 0 llle eese 20 complement 2 1 RES noer d 105 COMPOSE 3 aste ted eR eU REQU REPpS 106 YAP Prolog User s Manual compound vcn uE ERR MUERTE tees ee 32 e EEN 109 CONGA atom EE 109 COUVIISH EE EE ER EE 35 Copy term Naty ii uio wee ERE VERRE eR 112 create mutable 2 siii ker bis REES ER 67 current char conversion 2 45 current input l cee bee eR beg 42 Current key 2 Loud eni tcr ERU di tha 59 current EE 72 current module 2 ea er speeds 72 current miutex 3 EE 146 ett TEEN 80 Current output 1 RTE ere dE eg 42 current Dredicate 000 57 current_prolog_flag 2 00 eee eee eens 80 curtent stream ee Ab aud 42 currentthr ad 2 since ae ganda die ieas 141 cyclic termi Li eee eee rete ee Rr DE RR cen 101 D datime 1 dene rre pUprbRe IER PUPPES 98 del agoe id Lisci tannins cag E bre EV 84 EE EE 112 deliedses 3325 ere EA 105 del max assoc A ee meee eere tem 84 delmincassoC 4 sic acre eta oes o ueteres 84 del vertiGes B edt dE NEEN ge eds 104 delete 3 i ese deet oi sariei BrE STILURI E 87 delete hle 1 Alge
54. del ma x 4 oink bh ws siia RIRs 92 rb del umnin 4 o uoces ERG ads IP 92 rbodelete 3 2 bebo dos Scis 92 PD delete 4 s ce cd nerds dari S 8 ace ak ee 92 rb enpty i EE 92 FO Gebuer MER PR NES 92 rb keys 2 alus maie une edet Dis 93 rib lookup 3 eli iteLk iege ea eR dd 92 rb lookupall 3 2eter ER UpREBRDURE RS 92 rb ma p 3 2 adqrenebdmee d RR RP Rd dere 93 TD dx e lene Me EE E 93 rb MIN S EEN 93 TO EE 92 rb next A4 oo cette eee 93 rb partial map A sess EAR Sen d 93 rb previous 4 2 4p bc Dre Rope gre 93 rb size 2 ed EE Weder erem 93 rb pdate 4 Segelen gege 93 fb visit 2 EE 93 reachable 3 NENNEN chee ce a ER 106 read 1 ssc ee ketenes eee ees eee diri eb ete 44 Tead 2 7 20 oed du Seige cart be RE DEERE anes 50 read from chars cce ee 97 read term 2 ENEE 44 read ber EE 50 TOCONSUIT 1 poole enti deeoneun be Geese de 19 LOCOTdA S A deet E dEr poe beu pese 58 59 recorda Bt Sieve ces be by Mode eR TS 58 recordaifnot 3 EE 59 60 recorded 3 Eege A A ee liebe de 59 r cordz 8 EE 58 lee at o EE 58 TECOFAZIFNHOC EE 60 Tegep EE 94 e EE 94 remove duplicates eee eae 88 202 remove from patbh l sss 21 rename 2 ul lseise4i rr ad Ps ab bd rs 64 rename file see enne 99 repeat een ARA v ere EEN AE aM RR E 28 reset op Counters esses 153 resize static array 3 sss 71 TESTOR EE 22 retract l EE 56 EE 58 TOCKACCALL EE 56 feverse 2 2 2 EE BEE ende 88 runti
55. eR EE 97 head term ics kee Es hee eh pode 44 read term le npe Re Robe eR PRERRR 50 recorda 3 ect d eee UE ERES 59 recorda at 3 dE dE AE 58 recordaifnot 3 vee croce t beret eed rogi 59 60 TECOLdZAb EE 58 recordzifnot 3 EE 60 EE Ed Ee ova ees EPE E 94 resexp A obs ein sph ite ic EE ies 94 remove duplicates 2 0 000000005 88 remove from path 1 secsi predisernerte rris 21 rename DUSEL ae de ee AE Ae DERE 99 reset op Countere 153 resize static array 3 eee 71 Yestote T iue be spre ed ad puede alae P ERA 22 Yettact Le se used quen dye EE SE 56 retractall L dieere Pe ee 56 reverse uscd ects she ARP EE E E ENUE der Db 88 S same length 2recri prute ERE HELPER 88 SAVED cae etu RAE HERE UR de RR Das 22 save program l i see ex eR Reg xe 22 save program 2 cesse paoi abam ARTE ee AM 22 gelet rrer ronimine E EEPE PIS Qd 88 Selectlist 3 ciacdagasseasase REN 83 serve queue 3 serei rren ra cee eee eee 91 Set rnpub 1 EE 42 set output lis sper cons ice dere A Boge EU EE 42 Set prolog lag 2 ge neos pt e onr annua 80 set stream position 2 lssesseesss 42 EE 60 setarg 3n iss sagh SIRE UE sues REPE DEN ef 67 EE 109 setrand T tags EEr see 92 SHOU OS EE asleep EE EEN sede 100 SHOW DEE NAME EE 100 101 show_op counbers 1 58 EE te ER 153 show op by eroup sees eee eee 153 Show table I REES E 149 Sung MC 32 Slap 2 i sborerkseeenRe rv bd RE IDA CMPTU LE Hes 51 sleep Lupe reve wi heap E
56. eei Ren teeta eis OPERE 14 3 2 1 2 Floating point Number 15 3 2 2 Character Strings 0 045 sees ter a nocet been qas 15 SE WEE 16 O2A VariableS 44 4 danced daa eed na HU e web a o educa 16 2 2 5 Punctuation Tokens rassaa pisa cdd e EREECHEN aea 17 i250 EE 17 4 Loading PEOBP IS EE EE 19 4 1 Program loading and updating eee eee 19 4 2 Changing the Compiler s Bebhavior sese else 19 4 8 Saving and Loading Prolog States e 22 5 The Module Systenm axcn rmn 23 51 Module Concepts icerum AR EE eDopbe Ue Ed d A 23 5 2 Defining a New Module 24 53 Using Modules is used EEN NEES SEENEN FUR e 24 5 4 Meta Predicates in Module 25 ii YAP Prolog User s Manual 6 Built In Predicates es 27 6 1 Control Predicates 0 id dot eee ccc tne neces 27 6 2 Handling Undefined Procedures 0 00 cece cece eens 31 6 3 Predicates on terms 45 d dE an ead bad eae Ge eee eee d be 32 6 4 Comparing Iemms cece eee eaa 35 6 5 Arithinetie scien eee cheek ee eka es ae bend e ed RR EO 37 pb 1 0 RE EE eae 40 6 6 1 Handling Streams and les 40 6 6 2 Handling Streams and les 43 66 3 Handling Input Output of Terms 2 2220 0cascavedeasess 44 6 6 4 Handling Input Output of Characters 48 6 6 5 Input Output Predicates applied to Streams 50 6 6 6 Compatible C Prolog predicates for Terminal I O 51 6 0 0 Controlling Input OMG pu et ear E Rack RR od ede 51 6
57. entered just after committing to the rule 12 4 2 Tracing Tracing is enabled with the chr_trace 0 predicate and disabled with the chr_notrace 0 predicate When enabled the tracer will step through the call exit fail wake and apply ports accepting debug commands and simply write out the other ports The following debug commans are currently supported CHR debug options lt cr gt creep c creep s skip g ancestors n nodebug b break a abort f fail help h help Their meaning is creep Step to the next port skip Skip to exit port of this call or wake port Chapter 12 CHR Constraint Handling Rules 133 ancestors Print list of ancestor call and wake ports nodebug Disable the tracer break Enter a recursive Prolog toplevel See break 0 abort Exit to the toplevel See abort 0 fail Insert failure in execution help Print the above available debug options 12 4 3 CHR Debugging Predicates The chr module contains several predicates that allow inspecting and printing the content of the constraint store chr_trace 0 Activate the CHR tracer By default the CHR tracer is activated and deacti vated automatically by the Prolog predicates trace 0 and notrace 0 chr_notrace 0 De activate the CHR tracer By default the CHR tracer is activated and deac tivated automatically by the Prolog predicates trace 0 and notrace 0 chr leash O Define the set of CHR ports on which the CHR tracer asks for user intervent
58. 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 In put 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 9 2 Coroutining 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 condi tions 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 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 b
59. in the heap 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 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 Chapter 7 Library Predicates 87 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 min of heap Heap Key1 Datum1 Key2 Datum2 Returns the smallest Key1 and second smallest Key2 pairs in the heap without deleting them 7 5 List Manipulation The following list manipulation routines are available once included with the use module library lists command 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 delete List Element Residue True when List is a list in which Element may or may not occur and Residue is a copy of List with all elements identical to Element deleted flatten List FlattenedList Flatten a list of lists List into a single list FlattenedList flatten 11 2 31 4 5 6 7 8 L L 1 2 3 4 5 6 7 8 no is_list List True when List is a proper list That is List is bound to the em
60. int HeapSize int StackSize int Trail Size int NumberofWorkers int SchedulerLoop int DelayedReleaseLoad int argc char argv int ErrorNo and char ErrorCause The function returns an integer which indicates the current status If the result is YAP BOOT ERROR booting failed If SavedState is not NULL try to open and restore the file SavedState Initially YAP will search in the current directory If the saved state does not exist in the current directory YAP will use either the default library directory or the directory given by the environment variable YAPLIBDIR Note that currently the saved state must be loaded at the same address where it was saved If HeapSize is different from 0 use HeapSize as the minimum size of the Heap or code space If StackSize is different from 0 use HeapSize as the minimum size for the Stacks If TrailSize is different from 0 use TrailSize as the minimum size for the Trails The NumberofWorkers NumberofWorkers and DelayedReleaseLoad are only of inter est to the or parallel system The argument count argc and string of arguments argv arguments are to be passed to user programs as the arguments used to call YAP If booting failed you may consult ErrorNo and ErrorCause for the cause of the error or call YAP_Error ErrorNo 0L ErrorCause to do default processing e void YAP_PutValue Atom at YAP Term value Associate the term value with the atom at The term value must be a constant This functionality is
61. k quasi leap similar to leap but faster since the computation history is not kept useful when leap becomes too slow s skip YAP will continue execution without showing any messages until returning to the current activation Spy points will be ignored in this mode This command is meaningless and therefore illegal in the fail and exit ports t fast skip similar to skip but faster since the computation history is not kept useful when skip becomes too slow q quasi leap YAP will continue execution until a port of a spied predicate is found or until returning to the current activation f fail forces YAP to fail the goal proceeding directly to the fail port The command is not available in the fail port r retry after this command YAP will retry the present goal and so go back to the call port Note that any side effects of the goal will not be undone This command is not available at the call port a abort execution will be aborted and the interpreter will return to the top level n nodebug stop debugging but continue execution The command will clear all active spy points leave debugging mode and continue execution 158 YAP Prolog User s Manual 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 s
62. lives on the Prolog global stack This implies that lookup time is indepen dent 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 e They support both global assignment using nb_setval 2 and backtrackable assignment using b setval 2 e Only one value which can be an arbitrary complex Prolog term can be associated to a variable at a time e Their value cannot be shared among threads Each thread has its own namespace and values for global variables e Currently global variables are scoped globally We may consider module scoping in future versions Both b setval 2 and nb setval 2 implicitely 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 after the registration b_setval Name Value Associate the term Value with the atom Name or replaces the currentl
63. of A The ISO Prolog standard dictates that atom_chars 2 should unify the sec ond argument with a list of one char atoms and not the character codes For compatibility with previous versions of YAP and with other Prolog imple mentations YAP unifies the second argument with the character codes as in atom_codes 2 Use the set_prolog_flag to_chars_mode iso to obtain ISO standard compatibility atom_codes A L 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 concat As 4 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 atomic concat 4s 74 The predicate holds when the first argument is a list of atoms 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 atom_concat A1 A2 7A The predicate holds when the first argument and second argument are atoms and the third unifies with the atom obtained by concatenating the first two arguments atom_length A I ISO The predicate holds when the first argument is an atom and the second unifies with the number of characters forming that atom atom concat 4
64. only allow asserting clauses for dynamic predicates This is also as specified in the ISO standard YAP allows asserting clauses for static predicates The current version of YAP supports this feature but this feature is deprecated and support may go away in future versions abolish PredSpec ISO Deletes the predicate given by PredSpec from the database If PredSpec is an unbound variable delete all predicates for the current module The specification must include the name and arity and it may include module information Under iso language mode this built in will only abolish dynamic procedures Under other modes it will abolish any procedures abolish P N Deletes the predicate with name P and arity N It will remove both static and dynamic predicates 56 YAP Prolog User s Manual assert_static C Adds clause C to a static procedure Asserting a static clause for a predicate while choice points for the predicate are available has undefined results asserta_static C Adds clause C to the beginning of a static procedure assertz_static C Adds clause C to the end of a static procedure Asserting a static clause for a predicate while choice points for the predicate are available has undefined results The following predicates can be used for dynamic predicates and for static predicates if source mode was on when they were compiled clause H B ISO A clause whose head matches H is searched for in the program Its head
65. ordered list L 94 YAP Prolog User s Manual 7 11 Regular Expressions 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 expres sion 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 lida 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 ex pression a range see below matching any single character ma
66. predicate default local use local scheduling for this predicate exec_answers use complete tries as code default load_answers use complete tries as a consumer somewhat less efficient but creates less choice points abolish_table PredIndicator Remove tables for PredIndicator show_table PredIndicator Print out the contents of the table generated for PredIndicator table_statistics PredIndicator Print out some information on the current tables for PredIndicator 150 YAP Prolog User s Manual Chapter 17 Tracing at Low Level 151 17 Tracing at Low Level It is possible to follow the flow at abstract machine level if YAP is compiled with the flag LOW_LEVEL_TRACER Note that this option is of most interest to implementers as it quickly generates an huge amount of information Low level tracing can be toggled from an interrupt handler by using the option T There are also two built ins that activate and deactivate low level tracing start_low_level_trace Begin display of messages at procedure entry and retry stop_low_level_trace Stop display of messages at procedure entry and retry Note that this compile time option will slow down execution 152 YAP Prolog User s Manual Chapter 18 Profiling the Abstract Machine 153 18 Profiling the Abstract Machine Implementors may be interested in detecting on which abstract machine instructions are executed by a program The ANALYST flag can give WAM level informati
67. predicate is available number of clauses ClauseCount Number of clauses in the predicate definition Always one if exter nal or built in 58 YAP Prolog User s Manual 6 7 3 Using Data Base References Data Base references are a fast way of accessing terms The predicates erase 1 and instance 1 also apply to these references and may sometimes be used instead of retract 1 and clause 2 assert C R The same as assert C see Section 6 7 1 Modifying the Database page 55 but unifies R with the database reference that identifies the new clause in a one to one way Note that asserta 2 only works for dynamic predicates If the predicate is undefined it will automatically be declared dynamic asserta C R The same as asserta C but unifying R with the database reference that iden tifies the new clause in a one to one way Note that asserta 2 only works for dynamic predicates If the predicate is undefined it will automatically be declared dynamic assertz C R The same as assertz C but unifying R with the database reference that iden tifies the new clause in a one to one way Note that asserta 2 only works for dynamic predicates If the predicate is undefined it will automatically be declared dynamic retract C R Erases from the program the clause C whose database reference is R The predicate must be dynamic 6 8 Internal Data Base Some programs need global information for e g counting or collecting data ob
68. protected code fails or raises an exception For most common cases use with_mutex 2 wich provides a safer way for handling prolog level mutexes mutex_trylock MutexId As mutex_lock 1 but if the mutex is held by another thread this predicates fails immediately mutex_unlock MutexId Unlock the mutex This can only be called if the mutex is held by the calling thread If this is not the case a permission_error exception is raised 146 YAP Prolog User s Manual mutex unlock all Unlock all mutexes held by the current thread This call is especially useful to handle thread termination using abort 0 or exceptions See also thread signal 2 current mutex MutexId ThreadId Count Enumerates all existing mutexes If the mutex is held by some thread ThreadId is unified with the identifier of te holding thread and Count with the recursive count of the mutex Otherwise ThreadId is and Count is 0 Chapter 15 Parallelism 147 15 Parallelism 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 fol lowing restrictions are of note e YapOr currently only supports
69. seen YAP Prolog User s Manual Closes the current output stream and the user s terminal becomes again the current output stream It is important to remember to close streams after having finished using them as the maximum number of simultaneously opened streams is 17 If Sis a currently opened input stream then it is assumed to be the current input stream If S is an atom it is taken as a filename If there is no input stream currently associated with it then it is opened for input and the new input stream thus created becomes the current input stream If it is not possible to open the file an error occurs If there is a single opened input stream currently associated with the file it becomes the current input stream if there are more than one in that condition then one of them is chosen When S is a stream not currently opened for input an error may be reported depending on the state of the file errors flag If S is neither a stream nor an atom the predicates just fails The current input stream is unified with S Closes the current input stream see 6 7 6 6 3 Handling Input Output of Terms read T ISO Reads the next term from the current input stream and unifies it with T The term must be followed by a dot and any blank character as previously defined The syntax of the term must match the current declarations for op erators see op If the end of stream is reached T is unified with the atom end o
70. set the argument to a goal to be executed before entering the top level If unbound show the current goal or true if none is presented Only the first solution is considered and the goal is not backtracked into typein_module If bound set the current working or type in module to the argu ment which must be an atom If unbound unify the argument with the current working module unknown ISO Corresponds to calling the unknown 2 built in update_semantics Define whether YAP should follow immediate update semantics as in C Prolog default logical update semantics as in Quintus Prolog SICStus Prolog or in the ISO standard There is also an intermediate mode logical_assert where dynamic procedures follow logical semantics but the internal data base still follows im mediate semantics user_error If the second argument is bound to a stream set user_error to this stream If the second argument is unbound unify the argument with the current user_error stream Chapter 6 Built In Predicates 79 user_input By default the user_error stream is set to a stream corresponding to the Unix stderr stream The next example shows how to use this flag open dev null append Error alias mauri tripa Error stream 3 no set prolog flag user error mauri tripa close mauri tripa yes K We execute three commands First we open a stream in write mode and give it an alias in this
71. stream read the next byte from that stream and unify its code with C get_char S C ISO If C is unbound or is an atom representation of a character and the stream S is a text stream read the next character from that stream and unify its representation as an atom with C Chapter 6 Built In Predicates 51 get_code S C ISO If C is unbound or is a character code and the stream S is a text stream read the next character from that stream and unify its code with C peek_byte S C ISO If C is unbound or is a character code and S is a binary stream read the next byte from the current stream and unify its code with C while leaving the current stream position unaltered peek_char S C ISO If C is unbound or is an atom representation of a character and the stream S is a text stream read the next character from that stream and unify its representation as an atom with C while leaving the current stream position unaltered peek_code S C ISO If C is unbound or is an atom representation of a character and the stream S is a text stream read the next character from that stream and unify its representation as an atom with C while leaving the current stream position unaltered skip S C Like skip 1 but using stream S instead of the current input stream tab S N The same as tab 1 but using stream S nl S Outputs a new line to stream S 6 6 6 Compatible C Prolog predicates for Terminal I O ttyput N As
72. term of the form rand X Y Z describing the current state of the random number generator random Number Unify Number with a floating point number in the range 0 1 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 randseq LENGTH MAX Numbers Unify Numbers with a list of LENGTH unique random integers in the range 1 MAX 92 YAP Prolog User s Manual randset LENGTH MAX Numbers Unify Numbers with an ordered list of LENGTH unique random integers in the range 1 MAX 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 7 10 Red Black Trees 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 based on Introduction to Algorithms second edition by Cormen Leiserson Rivest and Stein The library includes routines to insert lookup and delete elements in the tree rb_new T Create a new tree rb empty T Succeeds if tree T is empty is_rbtree T Check whether T is a valid red black tree rb_insert T0 Key Value TF Add an element with key Key and Value to
73. used by YAP as a simple way for controlling and communicating with the Prolog run time Chapter 22 Using YAP as a Library 173 e YAP_Term YAP_Read int void GetC Parse a Term using the function GetC to input characters e YAP_Term YAP_RunGoal YAP_Term Goal Execute query Goal and return 1 if the query succeeds and 0 otherwise The predicate returns 0 if failure otherwise it will return YAP_Term Note that YAP_Term may change due to garbage collection so you should use something like t YAP RunGoal t if t 0 return FALSE If the execution fails garbage collection might still have changed the term so you should not use the input argument again An alternative is to use slots as shown next long sl YAP InitSlot scoreTerm out YAP_RunGoal t t YAP GetFromSlot s1 YAP RecoverSlots 1 if out 0 return FALSE Slots are safe houses in the stack preserved by the garbage collector and the stack shifter In this case we use a slot to preserve t during the execution of YAP RunGoal When the execution of t is over we read the possibly changed value of t back from the slot sl and tell YAP that the slot sl is not needed and can be given back to the system e int YAP RestartGoal void Look for the next solution to the current query by forcing YAP to backtrack e int YAP Reset void Reset execution environment similar to the abort 0O built in This is useful when you want to start a new query before asking
74. when append _ Suffix List holds sum_list Numbers Total True when Numbers is a list of numbers and Total is their sum 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 Chapter 7 Library Predicates 89 max_list Numbers Max True when Numbers is a list of numbers and Max is the maximum min_list Numbers Min True when Numbers is a list of numbers and Min is the minimum 7 6 Ordered Sets 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 list_to_ord_set List Set Holds when Set is the ordered representation of the set represented by the unordered representation List 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 ord_add_element Seti Element Set2 Inserting Element in Set1 returns Set2 It should give exactly the same result as merge Seti Element Set2 but a bit faster and certainly more clearly The same as ord in
75. with a number and the argument L must be unifiable with an atom representing the number char code A I 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 sub atom A Bef Size After At out ISO True when A and At out are atoms such that the name of At out has size Size and is a substring 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 substrings of A numbervars T N1 Nn Instantiates each variable in term T to a term of the form VAR CI with I increasing from N1 to Nn ground T Succeeds if there are no free variables in the term T arg N T A 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 functor T F N The top functor of term T is named F and has arity N Chapter 6 Built In Predicates 35 When T is not instantiated F and
76. write or append the file is not writable open F M S Opts ISO close S Opens the file with name F in mode M read write or append returning S unified with the stream name and following these options type T Specify whether the stream is a text stream default or a binary stream reposition Bool Specify whether it is possible to reposition the stream true or not false By default YAP enables repositioning for all files except terminal files and sockets eof_action Action Specify the action to take if attempting to input characters from a stream where we have previously found an end of file The possible actions are error that raises an error reset that tries to reset the stream and is used for tty type files and eof_code which generates a new end of file default for non tty files alias Name Specify an alias to the stream The alias Name must be an atom The alias can be used instead of the stream descriptor for every operation concerning the stream The operation will fail and give an error if the alias name is already in use YAP allows several aliases for the same file but only one is returned by stream_property 2 ISO Closes the stream S If S does not stand for a stream currently opened an error is reported The streams user_input user_output and user_error can never be closed By default give a file name close 1 will also try to close a corresponding open
77. 0 puis 64 update array S sce dere x rre ber dva T V variable mm Lerm ersrsrtronie i iie eta 102 with pre D I neg ce ida ew nice ony orero E 145 working directory 2 000 e eee eee 110 write EE 52 write depth 9 iussi sb Bes pea 52 Y yap Hag 2 isilikleeL ieee AEN REI 73 23 3 Compatibility with the ISO Prolog standard The Prolog standard was developed by ISO IEC JTC1 SC22 WGI17 the international stan dardization working group for the programming language Prolog The book Prolog The Standard by Deransart Ed Dbali and Cervoni gives a complete description of this stan dard Development in YAP from YAP4 1 6 onwards have striven at making YAP compatible with ISO Prolog As such e YAP now supports all of the built ins required by the ISO standard and e Error handling is as required by the standard YAP by default is not fully ISO standard compliant You can set the language flag to iso to obtain very good compatibility Setting this flag changes the following e By default YAP uses immediate update semantics for its database and not logical update semantics as per the standard see Section 23 2 SICStus Prolog page 183 This affects assert 1 retract 1 and friends Calling set prolog flag update semantics logical will switch YAP to use logi cal update semantics e By default YAP implements the atom chars 2 see Section 6 3 Testing Terms page 32 and number chars 2 see Section 6 3
78. 000 di Ignore the next argument in the list of arguments format The i met the boregrove mimsy The met the boregrove Chapter 6 Built In Predicates 47 Tk 3 Nn gt NN Nr DH NR Ns Print the next argument with write_canonical format Good night k at 1 2 Good night a 1 2 Print N newlines where N defaults to 1 Print N newlines if at the beginning of the line where N defaults to 1 The next argument must be an integer and N is interpreted as a radix such that 2 lt N lt 36 the default is 8 format 2r Ox i6r r 150000 150000 150000 100100100111110000 0x249f0 444760 Note that the letters a z denote digits larger than 9 Similar to NR The next argument must be an integer and N is interpreted as a radix such that 2 lt N lt 36 the default is 8 format 2r Ox i6r r 150000 150000 150000 100100100111110000 0Ox249F0 444760 The only difference is that letters A Z denote digits larger than 9 Print the next argument with print 1 format Good night p a 1 2 Good night a 1 2 Print the next argument with writeq 1 format Good night q Hello 1 2 Good night Hello 1 2 The next argument must be a list of character codes The system then outputs their representation as a string where N is the maxi mum number of characters for the string N defaults to the length of the string form
79. 1 42 412 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 Al and A2 are unbound the built in will find all the atoms that concatenated give A12 number chars 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 34 YAP Prolog User s Manual number and the argument L with the list of the ASCII codes for the characters of the external representation of I The ISO Prolog standard dictates that number_chars 2 should unify the sec ond argument with a list of one char atoms and not the character codes For compatibility with previous versions of YAP and with other Prolog imple mentations YAP unifies the second argument with the character codes as in number_codes 2 Use the set_prolog_flag to_chars_mode iso to obtain ISO standard compatibility number_codes 7A L 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 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
80. 1 if the X evaluates to a positive integer 0 it if evaluates to 0 and 1 if it evaluates to a negative integer If X evaluates to a floating point number return 1 0 for a positive X 0 0 for 0 0 and 1 0 otherwise truncate X The float that is the integral value between X and 0 closest to X max X Y The greater value of X and Y min X Y The lesser value of X and Y Chapter 6 Built In Predicates 39 X Y X raised to the power of Y from the C Prolog syntax exp X Y X raised to the power of Y from the Quintus Prolog syntax X Y ISO X raised to the power of Y from ISO X N Y 180 Integer bitwise conjunction X Y Iso Integer bitwise disjunction X Y ISO Integer bitwise exclusive disjunction X Y Integer bitwise left logical shift of X by Y places X gt gt Y ISO Integer bitwise right logical shift of X by Y places X ISO Integer bitwise negation gcd X Y The greatest common divisor of the two integers X and Y msb X The most significant bit of the integer X X Evaluates to X for expression X Useful because character strings in Prolog are lists of character codes X is Y 10 C 0 is the same as X is Y 104C 48 which would be evaluated as X is Y 10 C 48 Besides numbers and the arithmetic operators described above certain atoms have a special meaning when present in arithmetic expressions pi The value of pi the ratio of a circle s circumference to its diameter e The
81. 101 system predicate 2 ssssseessessess 57 T S TEE Oe ene 51 table statistics 1 sig Add ie tr IRURE Ys 149 term hash 2 oe NEE e e RERO ED 101 term hash 4 llle SEENEN 101 term t0 atomj2 o eee te eee 109 term variables 2 s cesses emt 101 thread at exit 1 iios teens 140 thread create 3 geg c d RR aas 139 thread detach 1 age meteor 140 thread exit 1 iic ere RENE candies ees 140 thread get message 142 thread get message 0 cee eee eee 142 thread join 2 cee iad EE ERR ee Ber PES 139 thread local 1 directive 144 thread message queue create 1 142 thread message queue destroy 1 142 thread peek message 1l 142 thread self ei iac etr erbe ERR uds id 139 thread send message isses 141 thread setconcurrency 2 140 thread signal 2c ctos cnet te RE es 143 thread statistics 30 ae Add DEA eke Die 141 GT EE 30 time out 3 EE 103 GE EE 100 EE 106 Lop SOPU S A ee qs qu 106 transitive closure r ccce cri resede nimero epia 106 RANSPOSE EE 105 LEE 103 tree e Jet rouser deg dek Acte gen dg 103 tiyget NEMPE 51 t ygetO T canseketeRbPbtet e RR ZA ZS Rae eis 51 TEE 51 GEET 51 blyskip P 51 ttytab l isses ee ee e eene 51 YAP Prolog User s Manual U undgraph add edges 3 sssssssses 108 undgraph add vertices 3 108 undgraph complement 2 108
82. 2 VAP EE boise ised Sc cscs Geos Deere 172 VAP FastInit l niger oe DERE A d 172 yap flag 2 EE 73 YAP_FloatOfTerm C Interface function 163 YAP_FreeSpaceFromYap C Interface function SR Ee 165 YAP_FullLookupAtom C Interface function SE Mee 164 YAP Functor fTerm C Interface function ede dd sb eee Ria Poe Pad nb ad Gene ea 164 YAP GetValue 1 esee re 172 YAP_HeadOfTerm C Interface function 164 VAP STG EE 172 VAP Tritt ConStht EE 173 YAP_IntOfTerm C Interface function 163 YAP_IsApplTerm C Interface function 163 YAP_IsAtomTerm C Interface function 163 YAP_IsBigNumTerm C Interface function 163 YAP_IsDBRefTerm C Interface function 163 YAP_IsFloatTerm C Interface function 163 YAP_IsIntTerm C Interface function 163 YAP_IsNonVarTerm C Interface function 163 YAP_IsPairTerm C Interface function 163 YAP_IsVarTerm C Interface function 162 YAP_LookupAtom C Interface function 164 YAP_MkApplTerm C Interface function 164 YAP_MkAtomTerm C Interface function 164 YAP_MkBigNumTerm C Interface function 163 YAP_MkFloatTerm C Interface function 163 YAP_MkFunctor C Interface function 165 YAP Prolog User s Manual YAP_MkIntTerm C Interface function 163 YAP_MkNewApplTerm C Interface function EE ad 164 YAP_MkNewPairTerm C Interface function ENEE daft 164 YAP_MkPairTerm C Interface function 164 YAP_N
83. 2 e b9ereecdueene DRE eSI 32 loBpy lo ecco beta eee doa See 155 lnoBpyall O EE 155 e PME 28 MG A D e dee reunir ee 88 TVG OY 4h Ee Bee nade Oe 88 nth clause 3 orne ere de 56 nth recorded 3 ov ooo sade s Lente WAR 59 MEO Ds bo isep rio va nee hate sua EEN 87 NG OY ep ee ek tend del ene 88 EE 109 ol 32 number atom 2 venne 34 number chars 2 5e PIP See EE ME 33 number codes 21 de ers 34 number to chars 2 ccu eer RR 97 number to chars cece see 97 numbervars 3 EE 34 O on cleanup l EE 102 on signal 3 c4 E ege CREE redd 66 EE EE 30 EE 80 OPER EE 40 Open 4 e vea pen ien Sei 41 Predicate Index ord_add_element 3 0 0 0 cece eee eee ee 89 ord del element 3 eee eee 89 GE eere ppbPRRRRERR ERE ed 89 ord insert 3 eee 89 ord intersect 2 eee enne 89 Ord dntersect J34 Jo eG danke ds Qe ets 89 Ord intersect 4 i 2360 l2 blue Bee Oo 89 Ord List to assoc 2 EE 85 Ord Member EE 89 Ord S tEG WEE 89 ord setproduct 3 2 cog mete ES 90 Ord SuUbtfact 3 cnl au hiicfiu 90 ord syndiff 3 5 2 VLDE Rer babes dis 90 Ord u nionm 9 Sege RA Sok hays d A 90 Ord Uniono EE 90 ord union 4 EE 90 ordsubset 2 gla ERU RE eR 90 P pathi 4 iie ceo ne bc RR CHREREP ERR EEREPES 20 peek byte 1 e esr Ra tontin C ca Pug 49 peek byte 2 ipt erREDRIR o iina in a 51 peek char 1 ui Sg de dEn MEAs RA A 49 peek char 2 EE 51 peek code 1 AER ees 49 peek c de
84. 3 1 4 51 5 1 D V 1 3 5 7 20 Directed Graphs 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 dgraph_new Graph Create a new directed graph This operation must be performed before trying to use the graph Chapter 7 Library Predicates 107 dgraph_vertices Graph Vertices Unify Vertices with all vertices appearing in graph Graph dgraph_edges Graph Edges Unify Edges with all edges appearing in graph Graph dgraph_add_vertices Graph Vertices NewGraph Unify NewGraph with a new graph obtained by adding the list of vertices Vertices to the graph Graph dgraph_del_vertices Vertices Graph 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 dgraph_add_edges Graph Edges NewGraph Unify NewGraph with a new graph obtained by adding the list of edges Edges to the graph Graph 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 dgraph neighbors Vertex Graph Vertice
85. 3 5 2 4 3 4 1 2 7 5 5 6 7 8 NL NL 1 2 7 5 complement Graph NewGraph Unify NewGraph with the graph complementary to Graph In the next example 106 YAP Prolog User s Manual complement 1 3 5 2 4 3 0 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 BI 7 1 2 3 4 5 6 8 8 1 2 3 4 5 6 7 compose LeftGraph RightGraph NewGraph Compose the graphs LeftGraph and RightGraph to form NewGraph In the next example compose 1 2 2 3 2 41 3 11 2 4 T 1 2 L 1 4 2 1 2 4 3 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 top sort 138 219 219 139 _139 L L _138 _219 _139 top_sort Graph Sort0 Sort Generate the difference list Sort Sort0 as a topological sorting of graph Graph if one is possible transitive closure Graph Closure Generate the graph Closure as the transitive closure of graph Graph In the next example transitive closure 1 2 3 2 4 5 4 6 L L 1 2 3 4 5 6 2 4 5 6 4 61 reachable Node Graph Vertices Unify Vertices with the set of all vertices in graph Graph that are reachable from Node In the next example reachable 1 1 3 5 2 41
86. 6 8 Using Sockets From Map 52 6 7 Using the Clausal Data Base 54 6 7 1 Modification of the Data Base 55 6 7 2 Looking at the Data Base 56 6 7 3 Using Data Base References 00000 e eee eee eee 58 6 8 Internal Data age Aug SN ca eee dad coed dd eae dard oo 58 6 9 The Blackboard psr suc Eer Be eerte othe aes ea 61 6 10 Collecting Solutions to a Goal 0 eee eee 61 6 11 Grammar Rules em yore atk ID qe PUES 63 6 12 Access to Operating System Functionality 64 6 13 Term Modification 66 6 14 Profiling Prolog Programs 00 0 cess cece ee eee 67 6 15 Coounting EE 68 EE 69 6 17 Predicate Information 71 6 18 Miscellaneous si iv es eed bid Sege died ee hae 72 T Library Predicates 3 020460404 Rr 83 7 1 Apply Macros cence hh 83 152 Association E68 ous cave a ee el ed ud indeed d Se ede lexus 84 Co AN To KEE EEN 86 TA Heaps sick ering Age didn de aE ae ania EE eege 86 7 5 List Manipulation DE E dr eens 87 TO Ordered Sets cocer oor eredi qt ee edere ORE aoa 89 7 7 Pseudo Random Number Integer Generator Ls 90 17 8 TEE 90 7 9 Random Number Generator 91 GD Red Black Trees ee se bee RR RE dice 92 7 11 Regular bapressionz 0c cece cece rn 94 TAD Splay lre684 4 42142252 9 ed Fonte deh ek etd ds A ee 95 7 13 Reading From and Writing To Strings 96 7 14 Calling The Operating System from YAP 98
87. 70 static array to term 3 ccsrcrsrcreircirriseui 70 stream_property 2 00 cece eee rss 42 style checky 1s arr Enge SEA d 21 EE 34 SUMAEES A iuc reie ene ee Eao 83 sumlist 4 EE ER E E EE ER Seu b EX eth eU Ut eebe 64 T table statistics T uui cec tbe ERROR ete 149 term to atom 2 rd renee re e ARES 109 thread atelier erb ARENSE ped 140 thread create 3 coss treit EE See el 139 thread detach Leite d head 140 thread exit RE 140 thread get message 142 thread get message cece ee eee 142 thredd Am 7 ed EE d deed E 139 thread_local 1 directive 144 thread_message_queue_create 1 142 thread_message_queue_destroy 1 142 thread peek message l 142 thread sll Mees set defteg i 139 thread send message 141 thread setconcurrency 2 140 thread signal 2 cesses beses nents d dr 143 YAP Prolog User s Manual thread statistics 3 cerescussreicoriesrcsrteni 141 Ubros desi diva dey baad Seen aes 30 U undgraph add edges 3 108 undgraph add vertices o nuuuasrrrenne 108 undgraph complement 2 108 undgraph del edges ee eee eens 108 undgraph edges 2 eee e eee 108 undgraph neighbors 3 108 undgraph neighbours 3 108 undgraph_n w 1c essere teen ria 108 undgraph vertices 2 000000000 108 unhide ui coser eu pte pec rette RE 2
88. AS DBP FREE 1 tells us to use the bp register frame pointer as the emulator s program counter This seems to be stable and is now default On Sparc Solaris2 use YAP EXTRAS mno app regs DOPTIMISE ALL REGS FOR SPARC 1 and YAP will get two extra registers This trick does not work on SunOS 4 machines Note that versions of GCC can be tweaked to recognize different processors within the same instruction set e g 486 Pentium and PentiumPro for the x86 or Ultrasparc and Supersparc for Sparc Unfortunately some of these tweaks do may make Yap run slower or not at all in other machines with the same instruction set so they cannot be made default Last the best options also depends on the version of GCC you are using and it is a good idea to consult the GCC manual under the menus Invoking GCC Submodel Options Specifically you should check march XXX for recent versions of GCC EGCS In the case of GCC2 7 and other recent versions of GCC you can check 486 In order to take advantage of 486 specific optimizations in GCC 2 7 YAP EXTRAS m486 DBP FREE 1 Chapter 1 Installing YAP 5 Pentium YAP_EXTRAS m486 malign loops 2 malign jumps 2 malign functions 2 PentiumPro and other recent Intel and AMD machines PentiumPros are known not to require alignment Check your version of GCC for the best march option Super and UltraSparcs YAP EXTRAS msupersparc MIPS if have a recent machine and you need
89. Debug Program Arguments 6 You need the sockets and yap libraries Add ws2 32 lib yapdll lib to to to Project Project Settings Link Object Library Modules You may also need to set the Link Path so that VC will find yapd11 1lib 7 set Project Project Settings C C Preprocessor Additional Include Directories to include the YAPSRC VC include and YAPSRC include The syntax is YAPSRC VC include YAPSRC include 8 Build the system 9 Use Build Start Debug to boot the system and then create the saved state with YAPSRC pl init save program startup Z That s it you ve got Yap and the saved state The YAPSRC VC directory has the make files to build Yap4 3 17 under VC 6 0 1 3 2 Compiling Under SGI s cc YAP should compile under the Silicon Graphic s cc compiler although we advise using the GNUCC compiler if available 64 bit Support for 64 bits should work by using under Bourne shell syntax CC cc 64 YAP_SRC_PATH configure YAP Prolog User s Manual Chapter 2 Running YAP 9 2 Running YAP We next describe how to invoke Yap in Unix systems 2 1 Running Yap Interactively Most often you will want to use Yap in interactive mode Assuming that YAP is in the user s search path the top level can be invoked under Unix with the following command yap s n h n a n c IP HOST port filename All the arguments and flags are optional and have the following meaning print a sho
90. E NE tn teg 101 SOCket 2 cresce sce peru geen sie be PERS 53 Socket 4 is siciieb e EreRrir icu p Rie pb med 53 Socket aecept 2 esset re eor tari ceed es 54 Socket accepb 3 ius steil aduer re 54 Socket blnd 2 seg eh 24 an Eri E Oe 53 socket buffering pini ters 54 socket close 1 1 seite eR EORR sees 53 socket_conmect 3 oi eco pede RR E 53 Socket listen 2 i src ser RR RR ebes 53 socket select 5 esce stem qr dede 54 SOULCE Q 19 source mode 2 sa cced pau er EA a 19 EE EE 96 splay delete 4 see rer eon cds 96 Splay INNIS ees cien e REL DER X EREREDPS 96 Splayiinsert 4 EEN 96 Spl y JOHl Bi axis debated Creed ata ed 96 Splay Split ST cat ozss secado pra E Sea qu mI 96 Spy Write 2 peronra estn ES RET RENRES TUE 156 srandom 1 iiber at tas ded dree 40 start Joe Jevel race t unuusuurunnrnno 151 Static array a EAR EEN p raniad 70 71 static_array_location 4 0 000 70 static array Droperties sees 70 static array to term 3 sssssssessess 70 EE 72 stream Droberta 0 00 e eee ne 42 182 stream select 3 ee Ee PECORE ERS 42 Style checkt d i DRIED E pP en 21 Dee cc sosedoodeeteo tete UICE d 34 gublisU 2 5 de ec ot ook ned AE ed edad aetna 88 subsumes 2 sso ANERE 102 subeumes chk 7 00000 e ke ee eee 102 GENEE 88 GE 88 SUMALES EE 83 Sutolist 2 gaere eed deena dere dees 88 suinlist 4 ee a pats ade devin Er PR dace 83 SUMNOdES 4 oiaracea ride EE 83 EE 101 EE
91. ER miii ipi ete cies 41 open Char stream 0 eee ee 97 ord add element 2 e Geesien ttre ae iEi 89 ord del element 3 0 0 00 20 000s 89 ord disjot 2 uec iones Rate EP agn 89 ord msert 9 rel Ae dee 89 ord intersect 2 creas prt hot ere ERR E adus 89 ord intersect 3 eeng ER REY one 89 ord intersect A ioca ecc R EEN ud 89 ord list zto asso6 2 ven Cot ett Bega 85 ord member 2 eccleboiR EE decks da Ys 89 Ord seleqi2 sodas IM eI Pee eee tld 89 ord setproduct 3 i he rene 90 ord subtract 3 WEE 90 ord symdWf 3 EE 90 ord umion 2 ecco bee recibe e ee EP 90 ord union 3 cceieebee pb hebr ert REIS 90 ord WINONA ivi oes ee teem Cep Ee 90 OFASUDSEU 2 sisal otia pRpe M Uer bete ce s 90 P path l 442 rrr ERRARE 20 21 peek EE 49 peek byte 2 o2 se roen teed tates 51 EE 49 Deck bart EE ege rer ere tpai 51 p ek COde EE 49 peek code 2 ur irere ENER NEEN g 51 permutation 22 urdu er etre irp xS 88 phras 2 bececetexeee Ueber benene 64 phrase S s ephoetepseg ve bees da andes 64 Pid L ENEE 100 POPEN S EE hale seal 100 portray clause 1 seg EE ne 57 portray TEE 57 predicate_property 2 00 cece eee eee 57 EE 50 prohle data 3 iRerereRA deb deed EEN 68 prohled LEE EE 68 project_attributes 2 0 2 005 119 prolog file name 2 0 0 esse eee eee 22 prolog Haer ere deed week ade 80 prolog initializ tion l ess rerercresiccirerei 80 prolog load context 2 ssi seen benene 80 p
92. Elem after the Nth element of Rest nth 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 1 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 permutation 4List Perm True when List and Perm are permutations of each other remove duplicates List Pruned Removes duplicated elements from List Beware if the List has non ground elements the result may surprise you reverse List Reversed Irue when List and Reversed are lists with the same elements but in opposite orders same length Listi 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 select Element Set Residue True when Set is a list Element occurs in Set and Residue is everything in Set except Element things stay in the same order sublist Sublist List True when both append _ Sublist S and append S _ List hold suffix Suffix List Holds
93. Handling Input Output of Characters put N Outputs to the current output stream the character whose ASCII code is N The character N must be a legal ASCII character code an expression yielding such a code or a list in which case only the first element is used put_byte N ISO Outputs to the current output stream the character whose code is N The current output stream must be a binary stream put_char N ISO Outputs to the current output stream the character who is used to build the representation of atom A The current output stream must be a text stream Chapter 6 Built In Predicates 49 put_code N ISO Outputs to the current output stream the character whose ASCII code is N The current output stream must be a text stream The character N must be a legal ASCII character code an expression yielding such a code or a list in which case only the first element is used get C The next non blank character from the current input stream is unified with C Blank characters are the ones whose ASCII codes are not greater than 32 If there are no more non blank characters in the stream C is unified with 1 If end_of_stream has already been reached in the previous reading this call will give an error message getO C The next character from the current input stream is consumed and then unified with C There are no restrictions on the possible values of the ASCII code for the character but the character will be internally convert
94. It can be used to generate all the keys for the internal data base 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 key_statistics K Entries TotalSize 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 this key 60 YAP Prolog User s Manual get value 4 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 set value 4 4C 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 Valuel is Value 1 set value counter Valuel This predicate is YAP specific recordzifnot K T R If a variant of T is stored under key K fail Otherwise make term T the last record under key K and unify R with its reference This predicate is YAP specific recordaifnot K T R If a variant of T is stored under key K fail Otherwise make term T the first record under key K and unify R with its reference This predicate is YAP s
95. MEESPON O EE 80 KEE 80 KEE 104 vertices_edges_to_ugraph 3 104 W WALT Dickie bes payer ioe ed or eder 101 walltime statistics 2 option T3 WHET Mc 116 with mut x 2 EEN 145 with output to chars 2 eege RENE e 97 with output to chars seus 97 with output to chars 4 s esses 97 working directory 2 100 110 WED COM be bw andes 45 WELEG e re sah ne a GA oR LOR Ow Ina d 50 write depth 20 ts sad Ben dere cea wate 52 write depth 3 EE 52 write strings yap_flag 2 option 79 write term EE 45 write term 30 EE 50 write to chars 2 2 451 Rhe Ree PW 96 write to chars Z3 12 3 b b 2 e B dee hens doe 96 TEE 46 WELECOS ege ERR ERR ahi e 50 Y YAP_AllocSpaceFromYap C Interface function TEE 165 YAP_ArgOfTerm C Interface function 164 YAP_ArityOfFunctor C Interface function SE e e 165 YAP_AtomName C Interface function 164 YAP AtomOfTerm C Interface function 164 YAP_BigNumOfTerm C Interface function 163 YAP BufferToAtomList C Interface function YAP CallProlog C Interface function 166 YAP ClearExceptions O sess 173 YAP CloseAllOpenStreams C Interface function ii e eg Eee ddp 166 204 YAP Conpilelause l 172 YAP CGontinuetGosal 0 eee 172 YAP_cutfail C Interface function 167 YAP_cutsucceed C Interface function 167 YAP Endonsult 0 000 c cece eitia 174 YAP eeh adie oak Eugen re eee gia 17
96. NewGraph Unify NewGraph with a new graph obtained by adding the list of edges Edges to the graph Graph In the next example add_edges 1 3 5 2 4 3 4 5 5 1 6 1 7 1 8 1 6 2 3 3 2 5 7 9 2 4 5 NL NL 1 3 5 6 2 3 41 1 3 2 4 5 5 71 6 TD T LE S5 01 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 del edges 1 3 5 2 41 3 1 4 51 5 1 6 7 8 1 1 6 2 3 3 2 5 7 3 2 4 5 1 3 NL NL 1 5 2 4 3 2 11 5 D 6 ET T EH 8 1 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 0CIVI 2 In the next example transpose i 3 5 2 4 3 4 5 5 1 6 1 7 L1 8 1 NL NL 1 1 2 1 3 11 4 21 5 1 41 6 1 7 L1 8 1 Notice that an undirected graph is its own transpose 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 neighbors 4 1 3 5 2 4 3 4 1 2 T 51 5 1 6 E t L1 8 L s NL NL 1 2 7 5 neighbours Vertex Graph Vertices Unify Vertices with the list of neighbours of vertex Vertex in Graph In the next example 7 neighbours 4 1
97. Prolog does not provide all the functionality required from a modern Prolog system Moreover because most Prolog im plementations do not fully implement the standard and because the standard itself gives the implementor latitude in a few important questions such as the unification algorithm and maximum size for numbers there is not guarantee that programs compliant with this mode will work the same way in every Prolog and in every platform We thus believe this mode is mostly useful when investigating how a program depends on a Prolog s platform specific features stack_dump_on_error If on show a stack dump when Yap finds an error The default is off syntax_errors Control action to be taken after syntax errors while executing read 1 read 2 or read_term 3 deci0 Report the syntax error and retry reading the term fail Report the syntax error and fail default 78 YAP Prolog User s Manual error Report the syntax error and generate an error quiet Just fail system_options This read only flag tells which options were used to compile Yap Currently it informs whether the system supports coroutining depth_limit the low_level_tracer or parallelism rational trees tabling threads or the wam_profiler to chars mode Define whether YAP should follow quintus like semantics for the atom chars 1 or number chars 1 built in or whether it should follow the ISO standard iso option toplevel_hook If bound
98. REP EUM 29 EE 29 initialization O 2 9 oris Gece since eed ened eke 80 initialization 1 directive 21 18 assoc li c coccenbebereieb RR Hbee Rer ovS 85 HIJA PR 87 is mutable T Age 67 is rbtree lge deeg E 92 isstabled lis cidctatcie edule Ed E 149 J JOMEQUCUC ee fen aap himlene eee 91 jump queue 3 ie cc rars tere oii daria Pee dana 91 K key statistics 3525 per erris Frees de 59 key st tisties 4 sz cepere Een eet 59 IEN 100 L Ee EE 87 length queue 2 corre Rat tie REDE EEN 91 library directory i isses rm eR 21 22 Iist concat 2 pii ere P UFert P rr i ega 87 Det 2010 queue 3 cce epe 91 list_jump_queue 3 0 0 eee eee ee ene 91 list tOSASSOG Dink d bee Weed qe E dba Ze 85 Detten hen s sed ni en eE PRIORA IN 86 ENEE 89 List tO QUeUG 2 0 snake ener Eeer en 91 list to tbtre 2 niece crab here es ee A 93 list to tree 2 v eres peeve Fond 103 M make drectorg bb ARE 99 make oueue t rod RER SEENEN E 91 180 MAP as8806 2 ERAN need Ob Seabee aE As 85 Map assoo Q EE 85 Map tree S a stoke led eerte eR ES 103 IDApArgs B ccsdeemeet9er pee ber REI Rex pL 83 inaplist 2 ege e gefeiert 110 MaAplist 3 2 3 AE sse Ae e EE 83 110 inaplist 4 eege uh japoni epi e Eau 110 mapnodes 3 erg deb obe geg AS EE deed 83 MAK assoc 3 ne6nepebe RI hed ceded Pb ES 85 MAX list 2 gg Dette EE d pao wit 89 EE 87 mietaberchk 2 icici hei SEELEN SNE EE pig ikast 87 MET ZEN EE 89 meta_predicate 1 directi
99. RG2 YAP_ARG16 or with YAP_A N where N is the argument number starting with 1 In the present case the function uses just one local variable of type YAP_Term the type used for holding Yap terms where the integer returned by the standard unix function getpid is stored as an integer term the conversion is done by YAP_MkIntTerm Int Then it calls the pre defined routine YAP_Unify YAP_Term YAP_Term which in turn returns an integer denoting success or failure of the unification The role of the procedure init_my_predicates is to make known to YAP by calling YAP_UserCPredicate the predicates being defined in the file This is in fact why in the example above init_my_predicates was passed as the third argument to load_foreign_ files The rest of this appendix describes exhaustively how to interface C to YAP 21 1 Terms This section provides information about the primitives available to the C programmer for manipulating prolog terms Several C typedefs are included in the header file yap YapInterface h to describe in a portable way the C representation of prolog terms The user should write is programs using this macros to ensure portability of code across different versions of YAP The more important typedef is YAP_Term which is used to denote the type of a prolog term Terms from a point of view of the C programmer can be classified as follows uninstantiated variables instantiated variables integers floating point numbe
100. SICStus Prolog sicstus The current default is cprolog This flag affects update semantics leashing mode style checking 76 YAP Prolog User s Manual handling calls to undefined procedures how directives are inter preted when to use dynamic character escapes and how files are consulted max_arity ISO Read only flag telling the maximum arity of a functor Takes the value unbounded for the current version of YAP max_integer ISO Read only flag telling the maximum integer in the implementation Depends on machine and Operating System architecture and on whether YAP uses the GMP multi precision library If bounded is false requests for max_integer will fail max_tagged_integer Read only flag telling the maximum integer we can store as a single word Depends on machine and Operating System architecture It can be used to find the word size of the current machine min_integer ISO Read only flag telling the minimum integer in the implementation Depends on machine and Operating System architecture and on whether YAP uses the GMP multi precision library If bounded is false requests for min_integer will fail min_tagged_integer Read only flag telling the minimum integer we can store as a single word Depends on machine and Operating System architecture n_of_integer_keys_in_bb Read or set the size of the hash table that is used for looking up the blackboard when the key is an integer n_of_integer_keys_
101. Testing Terms page 32 built ins as per the original Quintus Prolog definition and not as per the ISO definition Chapter 23 Compatibility with Other Prolog systems 193 Calling set_prolog_flag to_chars_mode iso will switch YAP to use the ISO defi nition for atom_chars 2 and number_chars 2 e By default YAP fails on undefined predicates To follow the ISO Prolog standard use set prolog flag unknown error e Dy default YAP allows executable goals in directives In ISO mode most directives can only be called from top level the exceptions are set prolog flag 2 and op 3 e Error checking for meta calls under ISO Prolog mode is stricter than by default e The strict iso flag automatically enables the ISO Prolog standard This feature should disable all features not present in the standard The following incompatibilities between YAP and the ISO standard are known to still exist e Currently YAP does not handle overflow errors in integer operations and handles floating point errors only in some architectures Otherwise YAP follows IEEE arith metic Please inform the authors on other incompatibilities that may still exist 194 YAP Prolog User s Manual Appendix A Summary of Yap Predefined Operators 195 Appendix A Summary of Yap Predefined Operators The Prolog syntax caters for operators of three main kinds e prefix e infix e postfix Each operator has precedence in the range 1 to 1200 and this precedence is u
102. Ut d prr soto Eve SA Bes 42 forall 2 EE 110 ee 46 fOLMAG EEN 48 format touChars 3 obse is nate d e 96 format to chars 4 asses terr hasan eee 96 Iraglle omne Meda t RS RES C IPSEPQUPPRPRS 102 EEN 115 frozen 2 A sep RARI be EVER PERPE 116 G garbage collect 0 ee ee eee eere 30 garbage collect atome sees 30 TEE 30 pen ASsOC Bish kis steed eat eke hy es 85 BOLDE zoo eat melse are sine tesa abies UE IS aes 50 Gel a8806 9 cL te EE EEN Eden RE 85 EE 85 EE 112 etzathis 2 obo vede Ina aces Ere eodd s 112 Set atts 2 sortem os PERI eos ds 118 get byle l tous vbebeb RO PIPER EEIEEI TUS 49 Sel byte 2 lodo iere REPORTE UOTE DI 50 getchar l sei ke pete Cie e bre ERR 49 get char 2 gege adr PRA noone ey 50 get code Myo ir se aie kbs Tees eds 49 EE 51 get from heap ori cvs pang oss Ta aber 86 amp et label 8 in a iet eR E 103 get mutable 2 asser euet ae pU eene es 67 Get next assOC Are riesce Tae eE RE 85 get Droe aesoc i 0 cee eee eee 85 Bet value 2s seed eege kei Se 60 E MEET 50 GELEET edt eas 64 E e EE 91 goal expansion 8 eve se enge ne 63 ground T i teh nrc ses dee AE See s 34 BLOW READ Al ZA eve RIBERA PE ERA 31 EEN 31 H EE 30 head queue 2 00 e eee eee eee 91 he p s126 2 oxi thee REIN E eroi Fed 86 eap tolist 2 ebe Eed 86 hide MNA M 20 Iude predicate 1 isis Rem e Reps 20 host ad 1 ge Sege See ed px LARES 99 host name 1 22 sssebessioELee Rr ecu rere 99 I Ud cM E DRM I
103. VE_DATA is used to initialize the memory which will hold the information to be preserved across backtracking The first argument is the variable we shall use and the second its type Note that we can only use YAP_PRESERVE_DATA once so often we will want the variable to be a structure If the argument of the predicate is a variable the routine initializes the structure to be preserved across backtracking with the information required to provide the next solution and exits by calling continue_n100 to provide that solution If the argument was not a variable the routine then checks if it was an integer and if so if its value is positive and less than 100 In that case it exits denoting success with YAP_cut_succeed or otherwise exits with YAP_cut_fail denoting failure The reason for using for using the functions YAP_cut_succeed and YAP_cut_fail instead of just returning a non zero value in the first case and zero in the second case is that otherwise if backtracking occurred later the routine continue_n100 would be called to provide additional solutions The code required for the second function is static int continue_n100 void int n YAP_Term t YAP_Term sol YAP_ARG1 YAP PRESERVED DATA n100 data n100 data type n YAP IntOfTerm ni00 data gt next solution if n 100 4 t YAP_MkIntTerm n YAP_Unify sol t YAP_cut_succeed else YAP Unify sol n100 data gt next solution n100 data gt next solution
104. YAP User s Manual Version No value for VERSION Vitor Santos Costa Luis Damas Rog rio Reis and Ruben Azevedo Copyright 1989 2000 L Damas V Santos Costa and Universidade do Porto Permission is granted to make and distribute verbatim copies of this manual provided the copyright notice and this permission notice are preserved on all copies Permission is granted to copy and distribute modified versions of this manual under the con ditions for verbatim copying provided that the entire resulting derived work is distributed under the terms of a permission notice identical to this one Permission is granted to copy and distribute translations of this manual into another lan guage under the above conditions for modified versions Table of Contents Introduction 5453254352656 bade ee ed 1 l Installing YAP oue ee geg 3 1 1 Tuning the Functionality of VAb 200000 3 1 2 Tuning YAP for a Particular Machine and Compiler 4 13 Tuning YAP for GC 4 1 3 1 Compiling Under Visual Cat 6 1 3 2 Compiling Under SGI s cc 7 2 Running YAP scsi 9 9 9 ee EEN 9 2 1 Running Yap interactively sss 0 000 eee eee eee 9 2 2 Running Prolog les eese see enm n NEEN 10 3 VACA we cee veto EE RR Ted YE ees 13 3 1 Syntax of Terms lt 06 012 sega em eme ee ee ee eo 13 3 2 Prolog Tokes rneer miian beaks heed dad erred adole dos meee a 14 2 2 1 NUMBERS reee ueteri ade El ber es toed UR b Ripa on 14 9 2 1 1 Integers RR
105. YAP_LookupAtom char s YAP Atom YAP_FullLookupAtom char s char YAP AtomName YAP Atom t The function YAP_LookupAtom looks up an atom in the standard hash table The function YAP FullLookupAtom will also search if the atom had been hidden this is useful for system maintenance from C code The functor YAP AtomName returns a pointer to the string for the atom A pair is a Prolog term which consists of a tuple of two prolog terms designated as the head and the tail of the term Pairs are most often used to build lists The following primitives can be used to manipulate pairs YAP Term YAP MkPairTerm YAP Term Head YAP Term Tail YAP Term YAP_MkNewPairTerm void YAP Term AP HeadOfTerm YAP Term t YAP Term YAP TailOfTerm YAP Term t One can construct a new pair from two terms or one can just build a pair whose head and tail are new unbound variables Finally one can fetch the head or the tail A compound term consists of a functor and a sequence of terms with length equal to the arity of the functor A functor described in C by the typedef Functor consists of an atom and of an integer The following primitives were designed to manipulate compound terms and functors YAP_Term YAP MkApplTerm YAP Functor f unsigned long int n YAP Term args YAP Term YAP MkNewApplTerm YAP Functor f int n YAP Term YAP ArgOfTerm int argno YAP Term ts YAP Functor YAP_FunctorOfTerm YAP_Term ts The YAP_MkApp1Term function constructs a new term
106. _path D Remove D from YAP s directory search path style_check X Turns on style checking according to the attribute specified by X which must be one of the following single_var Checks single occurrences of named variables in a clause discontiguous Checks non contiguous clauses for the same predicate in a file multiple Checks the presence of clauses for the same predicate in more than one file when the predicate has not been declared as multifile all Performs style checking for all the cases mentioned above By default style checking is disabled in YAP unless we are in sicstus or iso language mode The style_check 1 built in is now deprecated Please use the set_prolog_ flag 1 instead no_style_check X Turns off style checking according to the attribute specified by X which has the same meaning as in style_check 1 The no_style_check 1 built in is now deprecated Please use the set prolog flag 1 instead multifile P ISO Instructs the compiler about the declaration of a predicate P in more than one file It must appear in the first of the loaded files where the predicate is declared and before declaration of any of its clauses Multifile declarations affect reconsult 1 and compile 1 when a multifile predicate is reconsulted only the clauses from the same file are removed Since Yap4 3 0 multifile procedures can be static or dynamic discontiguous G ISO Declare that the arguments are discontiguous pr
107. _signal 3 succeeds unless when called with an invalid signal name or one that is not supported on this platform No checks are made on the handler provided by the user sig_up Hangup SIGHUP in Unix Linux Reconsult the initialization files yaprc prologre and prolog ini sig usri and sig_usr2 User signals SIGUSR1 and SIGUSR2 in Unix Linux Print a message and halt A special case is made where if Callable is bound to default then the default handler is restored for that signal A call in the form on_signal S H H can be used to retrieve a signal s current handler without changing it It must be noted that although a signal can be received at all times the handler is not executed while Yap is waiting for a query at the prompt The signal will be however registered and dealt with as soon as the user makes a query Please also note that neither POSIX Operating Systems nor Yap guarantee that the order of delivery and handling is going to correspond with the order of dispatch 6 13 Term Modification 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 mutable variab
108. a 64 bit wide address space you can use the abi 64 bits or eabi option as in CC gcc mabi 64 configure Be careful At least for some versions of GCC compiling with g seems to result in broken code WIN32 GCC is distributed in the MINGW32 and CYGWIN packages The Mingw32 environment is available from the URL http www mingw org You will need to install the msys and mingw packages You should be able to do configure make and make install If you use mingw32 you may want to search the contributed packages for the gmp multi precision arithmetic library If you do setup Yap with gmp note that libgmp d11 must be in the path otherwise Yap will not be able to execute CygWin environment is available from the URL http www cygwin com and mirrors We suggest using recent versions of the cygwin shell The compi lation steps under the cygwin shell are as follows mkdir cyg YAPSRC configure enable coroutining NN enable depth limit NN enable max performance make make install By default Yap will use the enable cygwin no option to disable the use of the cygwin dll and to enable the mingw32 subsystem instead Yap thus will not need the cygwin dll It instead accesses the system s CRTDLL DLL C run time library supplied with Win32 platforms through the mingw32 interface Note that some older WIN95 systems may not have CRTDLL DLL in this case it should be sufficient to import the file from a newer WIN95 or WIN98 mach
109. 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 gt descendant X Y offspring X Y descendant X 2 amp offspring X Y descendant Y Z amp Fail Redo x 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 usually 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 like 1 call quicksort 1 2 3 38
110. acktracking Note that dynamic arrays do not have a type each element may be any Prolog term The static arrays 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 Cur rently elements of static arrays in YAP should have one of the following predefined types e byte an 8 bit signed character e unsigned byte an 8 bit unsigned character e int Prolog integers Size would be the natural size for the machine s architecture 70 YAP Prolog User s Manual e float Prolog floating point number Size would be equivalent to a double in C e atom a Prolog atom e dbref an internal database reference e 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 named or anonymous Most arrays will be named 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
111. ailable in YAP e YAP implements escape sequences as in the ISO standard SICStus Prolog implements Unix like escape sequences e YAP implements initialization 1 as per the ISO standard Use prolog_ initialization 1 for the SICStus Prolog compatible built in e Prolog flags are different in SICStus Prolog and in YAP e The SICStus Prolog on exception 3 and raise exception built ins correspond to the ISO built ins catch 3 and throw 1 e The following SICStus Prolog v3 built ins are not currently implemented in YAP note that this is only a partial list call cleanup 1 file search path 2 stream interrupt 3 reinitialize 0 help 0 help 1 trimcore 0 load files 1 load files 2 and require 1 The previous list is incomplete We also cannot guarantee full compatibility for other built ins although we will try to address any such incompatibilities Last SICStus Prolog is an evolving system so one can be expect new incompatibilities to be intro duced in future releases of SICStus Prolog 184 YAP Prolog User s Manual YAP allows asserting and abolishing static code during execution through the assert_ static 1 and abolish 1 built ins This is not allowed in Quintus Prolog or SICStus Prolog YAP implements rational trees and co routining but they are not included by default in the system You must enable these extensions when compiling the system YAP does not currently implement constraints The socket predicates although
112. ame 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 Section 6 6 7 I O Control page 51 lt full term resets to the default of ten the debugger s maximum write depth For more information about write depth 2 see Section 6 6 7 I O Control page 51 A alternatives show the list of backtrack points in the current execution The debugging information when fast skip quasi leap is used will be lost Chapter 20 Indexing 159 20 Indexing The indexation mechanism restricts the set of clauses to be tried in a procedure by using information about the status of a selected argument of the goal in YAP as in most com pilers the first argument This argument is 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 HINT 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 Th
113. ameOfFunctor C Interface function EE 165 YAP_OpenStream C Interface function 166 YAP_PRESERVE_DATA C Interface function EE 167 YAP_PRESERVED_DATA C Interface function EE 167 YAP PutValue 2 i00 0 dt dE 172 YAP Beat 2 S ite b e Sege AE Ee 173 YAP ReadBuffer C Interface function 165 YAP Reset 0 db v beer eels base ede 173 YAP RestartGoal O 0000 c eee eee 173 VAP RestartGoad tee oo cscs ene ere 173 VAP RunGoOal DEE 173 YAP StreamToFileNo C Interface function DEE 166 YAP_StringToBuffer C Interface function EEN 165 YAP TailO0fTerm C Interface function 164 YAP Unify C Interface function 165 YAP UserBackCPredicate C Interface function 2 2 2292s dh Dp UR Mr 167 YAP UserCPredicate C Interface function cT 167 YAP Write 3 ce sed ber RE ER PITE 173 YAP WriteBuffer 4 eee 173 YAPBINDIR AEN E 9 TAPLIBDER gt ceciren ee e Sh eae ee ue ee 10 TAPSGHAREDIB cv 20c 68ea saws HAS oR e eee ease x 10 Concept Index Concept Index A anonymous variable association lisse erare Pee ede eL P attribute declaration ssc codiriciririnsstiis attributed variables AM EE B BOONE erasana aa NaS C D declaration attribute E Efficient Directed Graphs lusus end OF Term 32 s csc seve head Rok IRE environment variables aananaanaanna F floating point number H reageiert Sg para ddd den pe abdea ada
114. an set the current module by using the built in module 1 Note that in this module system one can explicitly specify the source mode for a clause by prefixing a clause with its module say user a b In fact to specify the source module for a clause it is sufficient to specify the source mode for the clause s head user a b The rules for goals are similar If a goal appears in a text file with a module declaration the goal s source module is the declared module Otherwise it is the module the file is being loaded into or the type in module One can override this rule by prefixing a goal with the module it is supposed to be executed into say nasa launch apollo 13 will execute the goal 1aunch apollo 13 as if the current source module was nasa Note that this rule breaks encapsulation and should be used with care 24 YAP Prolog User s Manual 5 2 Defining a New Module A new module is defined by a module declaration module M L This predicate defines the file where it appears as a module file it must be the first declaration in the file M must be an atom specifying the module name L must be a list containing the module s public predicates specification in the form predicate_name arity The public predicates of a module file can be made accessible by other files through the predicates consult 1 reconsult 1 ensure_loaded 1 or use_ module 2 The non public predicates of a module file are not vi
115. and body are respectively unified with H and B If the clause is a unit clause B is unified with true This predicate is applicable to static procedures compiled with source active and to all dynamic procedures clause H B R The same as clause 2 plus R is unified with the reference to the clause in the database You can use instance 2 to access the reference s value Note that you may not use erase 1 on the reference on static procedures nth clause 4H I R Find the Ith clause in the predicate defining H and give a reference to the clause Alternatively if the reference R is given the head H is unified with a description of the predicate and I is bound to its position The following predicates can only be used for dynamic predicates retract C ISO Erases the first clause in the program that matches C This predicate may also be used for the static predicates that have been compiled when the source mode was on For more information on source 0 see Section 4 2 Setting the Compiler page 19 retractall G Retract all the clauses whose head matches the goal G Goal G must be a call to a dynamic predicate 6 7 2 Looking at the Data Base listing Lists in the current output stream all the clauses for which source code is available these include all clauses for dynamic predicates and clauses for static predicates compiled when source mode was on listing P Lists predicate P if its source code is available Ch
116. apter 6 Built In Predicates 57 portray_clause C Write clause C as if written by listing 0 portray_clause S C Write clause C on stream S as if written by listing O current atom 4 Checks whether A is a currently defined atom It is used to find all currently defined atoms by backtracking current predicate F ISO F is the predicate indicator for a currently defined user or library predicate F is of the form Na Ar where the atom Na is the name of the predicate and Ar its arity current predicate A P Defines the relation P is a currently defined predicate whose name is the atom A system predicate A P Defines the relation P is a built in predicate whose name is the atom A predicate property P Prop For the predicates obeying the specification P unify Prop with a property of P These properties may be built in true for built in predicates dynamic true if the predicate is dynamic static true if the predicate is static meta predicate M true if the predicate has a meta predicate declaration M multifile true if the predicate was declared to be multifile imported from Mod true if the predicate was imported from module Mod exported true if the predicate is exported in the current module public true if the predicate is public note that all dynamic predicates are public tabled true if the predicate is tabled note that only static predicates can be tabled in YAP Source true if source for the
117. ariable V in the term TT there is a new variable V in term TF 6 4 Comparing Terms The following predicates are used to compare and order terms using the standard ordering e variables come before numbers numbers come before atoms which in turn come before compound terms i e variables lt numbers lt atoms lt compound terms e variables are roughly ordered by age the oldest variable is put first e floating point numbers are sorted in increasing order e Integers are sorted in increasing order e atoms are sorted in lexicographic order e compound terms are ordered first by name then by arity of the main functor and finally by their arguments in left to right order compare C X Y As a result of comparing X and Y C may take one of the following values e if X and Y are identical 36 YAP Prolog User s Manual e lt if X precedes Y in the defined order e gt if Y precedes X in the defined order X Y 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 X fails but T X Y X Y succeeds X 2 fails but 7 X e gt i N succeeds X Y ISO Terms X and Y are not strictly identical X lt Y ISO Term X precedes term Y in the standard order X lt Y ISO Term X does not follow term Y in the standard orde
118. as a new seed for YAP s random number generator The argument should be an integer but floats are acceptable Notes e In contrast to previous versions of Yap Yap4 does not convert automatically between integers and floats e arguments to trigonometric functions are expressed in radians e if a non instantiated variable occurs in an arithmetic expression YAP will generate an exception If no error handler is available execution will be thrown back to the top level 6 6 I O Predicates Some of the I O predicates described below will in certain conditions provide error messages and abort only if the file errors flag is set If this flag is cleared the same predicates will just fail Details on setting and clearing this flag are given under 7 7 6 6 1 Handling Streams and Files open F M S ISO Opens the file with name F in mode M read write or append returning S unified with the stream name Chapter 6 Built In Predicates 41 At most there are 17 streams opened at the same time Each stream is either an input or an output stream but not both There are always 3 open streams user_input for reading user_output for writing and user_error for writ ing If there is no ambiguity the atoms user_input and user_output may be referred to as user The file_errors flag controls whether errors are reported when in mode read or append the file F does not exist or is not readable and whether in mode
119. as source_mode _ off compile_expressions After a call to this predicate arithmetical expressions will be compiled see example below This is the default behavior do_not_compile_expressions After a call to this predicate arithmetical expressions will not be compiled source do_not_compile_expressions yes user p X X is 2 3 8 end_of_file compile_expressions yes user q X X is 2 3 8 end_of_file listing p A A is 2 3 8 q A A is 22 hide Atom Make atom Atom invisible unhide Atom Make hidden atom Atom visible hide predicate Pred Make predicate Pred invisible to current predicate 2 listing and friends expand exprs 0 N Puts YAP in state N on or off and unify O with the previous state where On is equivalent to compile expressions and off is equivalent to do not compile expressions This predicate was kept to maintain compatibility with C Prolog path D Unifies D with the current directory search path of YAP Note that this search path is only used by YAP to find the files for consult 1 reconsult 1 and restore 1 and should not be taken for the system search path add to path 4D Adds D to the end of YAP s directory search path Chapter 4 Loading Programs 21 add_to_path D N Inserts D in the position of the directory search path of YAP specified by N N must be either of first or last remove_from
120. at The s are 4s woods lovely The woods are love Print the next argument with write 1 format Good night w Hello 1 2 Good night Hello 1 2 The number of arguments N may be given as an integer or it may be given as an extra argument The next example shows a small procedure to write a variable number of a characters write_many_as N format c N 0 a The format 2 built in also allows for formatted output One can specify column boundaries and fill the intermediate space by a padding character 48 YAP Prolog User s Manual NI Set a column boundary at position N where N defaults to the current position Neit Set a column boundary at N characters past the current position where N defaults to 8 Nt Set padding for a column where N is the fill code default is GPO The next example shows how to align columns and padding We first show left alignment format n Hello 16 n Hello Note that we reserve 16 characters for the column The following example shows how to do right alignment format tHello 16 n Hellox The t escape sequence forces filling before Hello We next show how to do centering format tHello t i64 n Hello The two t escape sequence force filling both before and after Hello Space is then evenly divided between the right and the left sides format S T L Print formatted output to stream S 6 6 4
121. ations and therefore he should try to avoid them whenever possible Chapter 6 Built In Predicates 55 dynamic P Declares predicate P or list of predicates P1 Pn as a dynamic predicate P must be written in form name arity dynamic god 1 a more convenient form can be used dynamic son 3 father 2 mother 2 or equivalently dynamic son 3 father 2 mother 2 Note a predicate is assumed to be dynamic when asserted before being defined dynamic predicate P Semantics Declares predicate P or list of predicates P1 Pn as a dynamic predicate following either logical or immediate semantics 6 7 1 Modification of the Data Base These predicates can be used either for static or for dynamic predicates assert C Adds clause C to the program If the predicate is undefined declare it as dynamic Most Prolog systems only allow asserting clauses for dynamic predicates This is also as specified in the ISO standard YAP allows asserting clauses for static predicates as long as the predicate is not in use and the language flag is cprolog Note that this feature is deprecated if you want to assert clauses for static procedures you should use assert_static 1 asserta C ISO Adds clause C to the beginning of the program If the predicate is undefined declare it as dynamic assertz C ISO Adds clause C to the end of the program If the predicate is undefined declare it as dynamic Most Prolog systems
122. bage_collect forces a garbage collection of the atoms in the data base Currently only atoms are recovered gc The goal gc enables garbage collection The same as yap_flag gc on nogc The goal nogc disables garbage collection The same as yap flag gc off Chapter 6 Built In Predicates 31 grow_heap Size Increase heap size Size kilobytes grow_stack Size Increase stack size Size kilobytes 6 2 Handling Undefined Procedures 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 through three different ways e By setting an YAP flag through the yap_flag 2 or set prolog flag 2 built ins This solution generalizes the ISO standard e By using the unknown 2 built in this solution is compatible with previous releases of YAP e By defining clauses for the hook predicate user unknown_predicate_handler 3 This solution is compatible with SICStus Prolog In more detail unknown 0 N Specifies an handler to be called is a program tries to call an undefined static procedure P The arity of N may be zero or one If the arity is 0 the new action must be one of fail warning or error If the arity is 1 P is an user defined handler and at run time the argument to the handler P will be unified with the undefined goal Note that N must be defined prior to cal
123. because almost any usage of these predicates is unsafe For example checking the existence of a thread before signalling it is of no use as it may vanish between the two calls Catching exceptions using catch 3 is the only safe way to deal with thread existence errors These predicates are provided for diagnosis and monitoring tasks Chapter 14 Threads 141 current_thread Id Status Enumerates identifiers and status of all currently known threads Calling cur rent_thread 2 does not influence any thread See also thread_join 2 For threads that have an alias name this name is returned in Id instead of the numerical thread identifier Status is one of running The thread is running This is the initial status of a thread Please note that threads waiting for something are considered running too false The Goal of the thread has been completed and failed true The Goal of the thread has been completed and succeeded exited Term The Goal of the thread has been terminated using thread exit 1 with Term as argument If the underlying native thread has exited using pthread_exit Term is unbound exception Term The Goal of the thread has been terminated due to an uncaught exception see throw 1 and catch 3 thread statistics Id Key Value Obtains statistical information on thread Id as statistics 2 does in single threaded applications This call returns all keys of statistics 2 although only information statistics about
124. 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 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 hostname address HOSTNAME IP_ADDRESS HOSTNAME is an host name and IP ADDRESS its IP address in number and dots notation 6 7 Using the Clausal Data Base Predicates in YAP may be dynamic or static By default when consulting or reconsulting predicates are assumed to be static execution is faster and the code will probably use less space Static predicates impose some restrictions in general there can be no addition or removal of clauses for a procedure if it is being used in the current execution Dynamic predicates allow programmers to change the Clausal Data Base with the same flexibility as in C Prolog With dynamic predicates it is always possible to add or remove clauses during execution and the semantics will be the same as for C Prolog But the programmer should be aware of the fact that asserting or retracting are still expensive oper
125. ber ResultO Result Convert the atom Number to the difference list of character codes Result Result0 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 open_chars_stream Chars Stream Open the list of character codes Chars as a stream Stream 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 CharsO 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 CharsQ0 with output to chars Goal Stream CharsO 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 The implementation of the character IO operations relies on three YAP built ins charsio open mem read stream Strin
126. by removing the smallest element of the list with Key and Val from the list Assoc Chapter 7 Library Predicates 85 empty assoc Assoc Succeeds if association list Assoc is empty 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 get_assoc Key Assoc Value If Key is one of the elements in the association list Assoc return the associated value 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 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 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 is_assoc Assoc Succeeds if Assoc is an association list that is if it is a red black tree 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 map_assoc Pred Assoc Succeeds if the unary predicate name Pred Val holds for every element in the association list map_assoc Pred Assoc New Given the binary predi
127. 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 54 YAP Prolog User s Manual socket_accept SOCKET STREAM 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 Socket accept SOCKET STREAM Accept a connection but do not return client information 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_select SOCKETS NEWSTREAMS TIMEOUT STREAMS READSTREAMS 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 descrip tor 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
128. case mauri_tripa Next we set user_error to the stream via the alias Note that after we did so prompts from the system were redirected to the stream mauri_ tripa Last we close the stream At this point YAP automatically redirects the user_error alias to the original stderr If the second argument is bound to a stream set user_input to this stream If the second argument is unbound unify the argument with the current user_input stream By default the user_input stream is set to a stream corresponding to the Unix stdin stream user_output version If the second argument is bound to a stream set user_output to this stream If the second argument is unbound unify the argument with the current user_output stream By default the user_output stream is set to a stream correspond ing to the Unix stdout stream Read only flag that giving the current version of Yap write_strings Writable flag telling whether the system should write lists of inte gers that are writable character codes using the list notation It is on if enables or off if disabled The default value for this flag is off 80 YAP Prolog User s Manual current_prolog_flag Flag Value ISO Obtain the value for a YAP Prolog flag Equivalent to calling yap_flag 2 with the second argument unbound and unifying the returned second argument with Value prolog_flag Flag OldValue NewValue Obtain the value for a YAP Prolog flag and then set it to a new value
129. cate 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 max assoc Assoc Key Value Given the association list Assoc Key in the largest key in the list and Value the associated value min_assoc Assoc Key Value Given the association list Assoc Key in the smallest key in the list and Value the associated value 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 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 86 YAP Prolog User s Manual 7 3 AVL Trees 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 avl insert Key Value T0 TF Add an elem
130. constraints to a set of variables This is useful when displaying the solution to a goal but may also be used to manipulate com putations The user defined project attributes 2 is responsible for implementing this projection 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 con straint 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 10 6 Attribute Examples 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
131. d 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 sleep Time system Block the current process for Time seconds 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 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 system Command Res Interface to system execute command Command and unify Res with the result wait PID Status Wait until process PID terminates and return its exits Status 7 15 Utilities On Terms 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 acyclic term Term Succeed if the argument Term is an acyclic term cyclic term Term Succeed if the argument Term is a cyclic term term_hash Term Hash If Term is ground unify Hash with a positive integer calculated from the struc ture of the term Otherwise the argument Hash is left unbound The range of the positive integer
132. designed to be compatible with SICStus Prolog are built ins not library predicates in YAP This list is incomplete The following differences only exist if the language flag is set to yap the default The consult 1 predicate in YAP follows C Prolog semantics That is it adds clauses to the data base even for preexisting procedures This is different from consult 1 in SICStus Prolog By default the data base in YAP follows immediate update semantics instead of logical update semantics as Quintus Prolog or SICStus Prolog do The difference is depicted in the next example dynamic a 1 assert a 1 retract a X X1 is X 1 assertz a X With immediate semantics new clauses or entries to the data base are visible in back tracking In this example the first call to retract 1 will succeed The call to assertz 1 will then succeed On backtracking the system will retry retract 1 Because the newly asserted goal is visible to retract 1 it can be retracted from the data base and retract a X will succeed again The process will continue generating integers for ever Immediate semantics were used in C Prolog With logical update semantics any additions or deletions of clauses for a goal will not affect previous activations of the goal In the example the call to assertz 1 will not see the update performed by the assertz 1 and the query will have a single solution Calling yap flag update semantics logical will switc
133. dicate load_foreign_files Files Libs InitRoutine should be used from inside YAP to load object files produced by the C compiler The argument ObjectFiles should be a list of atoms specifying the object files to load Libs is a list possibly empty of libraries to be passed to the unix loader 1d and InitRoutine is the name of the C routine to be called after the files are loaded to perform the necessary declarations to YAP of the predicates defined in the files YAP will search for ObjectFiles in the current directory first If it cannot find them it will search for the files using the environment variable YAPLIBDIR if defined or in the default library In a out systems YAP by default only reserves a fixed amount of memory for object code 64 Kbytes in the current version Should this size prove inadequate the flag c n can be passed to YAP in the command line invoking YAP to force the allocation of n Kbytes 21 9 Saving and Restoring Yap4 currently does not support save and restore for object code loaded with load foreign files We plan to support save and restore in future releases of Yap 21 10 Changes to the C Interface in Yap4 Yap4 includes several changes over the previous load foreign files interface These changes were required to support the new binary code formats such as ELF used in Solaris2 and Linux 170 YAP Prolog User s Manual All Names of YAP objects now start with YAP_ This is designed to avoid clash
134. e 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 importa
135. e predicate defined in the module is loaded as soon as a goal in the module is called or as soon as it becomes the current type in module current module M F Succeeds if M are current modules associated to the file F 6 18 Miscellaneous statistics 0 Send to the current user error stream general information on space used and time spent by the system statistics memory total 4784124 bytes program space 3055616 bytes 1392224 in use 1663392 freeg 2228132 maxi stack space 1531904 bytes 464 in use 1531440 freeg global stack 96 in use 616684 maxi local stack 368 in use 546208 max trail stack 196604 bytes 8 in use 196596 freeg 0 010 sec for 5 code 2 stack and 1 trail space overflows 0 130 sec for 3 garbage collections which collected 421000 bytes 0 000 sec for 0 atom garbage collections which collected 0 bytes 0 880 sec runtime 1 020 sec cputime 25 055 sec elapsed time The example shows how much memory the system spends Memory is divided into Program Space Stack Space and Trail In the example we have 3MB allocated for program spaces with less than half being actually used Yap also shows the maximum amount of heap space having been used which was over 2MB The stack space is divided into two stacks which grow against each other We are in the top level so very little stack is being used On the other hand the system did use a lot of global and local stack during the previous execution we refer the read
136. e Tree return its Val and unify Return with true Otherwise unify Return with null The variable New Iree unifies with the new tree splay_delete Key Val 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 splay init NewTree Initialize a new splay tree 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 Neu Tree 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 splay_join LeftTree RighTree NewTree Combine trees LeftTree and RighTree into a single treeNew Tree 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 splay_split Key Val Tree LeftTree RightTree Construct and return two trees LeftTree and RightTree where LeftTree con tains all items in Tree less than Key and RightTree contains all items in Tree greater than Key This operations destroys Tree 7 13 Reading From and Writing To Strings From Version 4 3 2 onwards YAP implements SICStus Prolog compatible String I O The library allows users to read from
137. e Yap as a library e INFODIR is where to store info files Usually usr local info usr info or usr share info make If the compilation succeeds try yap If you feel satisfied with the result do make install make install info will create the info files in the standard info directory make html will create documentation in html format in the predefined directory In most systems you will need to be superuser in order to do make install and make info on the standard directories 1 1 Tuning the Functionality of YAP Compiling Yap with the standard options give you a plain vanilla Prolog You can tune Yap to include extra functionality by calling configure with the appropriate options enable rational trees yes gives you support for infinite rational trees enable coroutining yes gives you support for coroutining including freezing of goals attributed variables and constraints This will also enable support for infinite rational trees enable depth limit yes allows depth limited evaluation say for implementing it erative deepening enable low level tracer yes allows support for tracing all calls retries and backtracks in the system This can help in debugging your application but results in performance loss enable wam profile yes allows profiling of abstract machine instructions This is useful when developing YAP should not be so useful for normal users 4 YAP Prolog User s Manual e enable condor y
138. e also provides the C application with a measure of control over the Yap Input Output system The first routine allows one to find a file number given a current stream int YAP_StreamToFileNo YAP_Term stream This function gives the file descriptor for a currently available stream Note that null streams and in memory streams do not have corresponding open streams so the routine will return a negative Moreover Yap will not be aware of any direct operations on this stream so information on say current stream position may become stale A second routine that is sometimes useful is void YAP_CloseAl10penStreams void This routine closes the Yap Input Output system except for the first three streams that are always associated with the three standard Unix streams It is most useful if you are doing fork The next routine allows a currently open file to become a stream The routine receives as arguments a file descriptor the true file name as a string an atom with the user name and a set of flags void YAP_OpenStream void FD char name YAP Term t int flags The available flags are YAP INPUT STREAM YAP OUTPUT STREAM YAP APPEND STREAM YAP PIPE STREAM YAP TTY STREAM YAP POPEN STREAM YAP BINARY STREAM and YAP SEEKABLE STREAM By default the stream is supposed to be at position 0 The argument name gives the name by which YAP should know the new stream 21 6 From C back to Prolog Newer versions of YAP allow for calling the Prolog
139. e is used when reading terms The default value for this flag is off except in sicstus and iso language modes where it is on character_escapes ISO Writable flag telling whether a character escapes are enables on or disabled off The default value for this flag is on debug ISO If Value is unbound tell whether debugging is on or off If Value is bound to on enable debugging and if it is bound to off disable debugging discontiguous_warnings If Value is unbound tell whether warnings for discontiguous predi cates are on or off If Value is bound to on enable these warnings and if it is bound to off disable them The default for YAP is off unless we are in sicstus or iso mode dollar_as_lower_case If off default consider the character a control character if on consider a lower case character double_quotes ISO If Value is unbound tell whether a double quoted list of characters token is converted to a list of atoms chars to a list of integers codes or to a single atom atom If Value is bound set to the corresponding behavior The default value is codes fast If on allow fast machine code if off default disable it Only available in experimental implementations Chapter 6 Built In Predicates 75 fileerrors If on fileerrors is on if off default fileerrors is disabled float_format gc EC margin gc trace host type index C library printf format specification
140. eam position P A term describing the position in the stream end_of_stream E Whether the stream is at the end of stream or it has found the end of stream and is past or whether it has not yet reached the end of stream eof_action A The action to take when trying to read after reaching the end of stream The action may be one of error generate an error eof_ code return character code 1 or reset the stream reposition B Whether the stream can be repositioned or not that is whether it is seekable type T Whether the stream is a text stream or a binary stream 6 6 2 Handling Streams and Files tell 4 S If S is a currently opened stream for output it becomes the current output stream If S is an atom it is taken to be a filename If there is no output stream currently associated with it then it is opened for output and the new output stream created becomes the current output stream If it is not possible to open the file an error occurs If there is a single opened output stream currently associated with the file then it becomes the current output stream if there are more than one in that condition one of them is chosen Whenever S is a stream not currently opened for output an error may be reported depending on the state of the file_errors flag The predicate just fails if S is neither a stream nor an atom telling S The current output stream is unified with S 44 told see S seeing S
141. ed Program Space Free Equivalent to heap runtime Time since Boot Time From Last Call to Runtime This gives the total cputime in milliseconds spent executing Prolog code not including garbage collections and stack shifts Note that until Yap4 1 2 the runtime statistics would return time spent on garbage collection and stack shifting stack_shifts Number of Heap Shifts Number of Stack Shifts Number of Trail Shifts Number of times YAP had to expand the heap the stacks or the trail More detailed information is available using yap flag gc trace verbose trail Trail Used Trail Free Space in kbytes currently being used and still available for the trail walltime Time since Boot Time From Last Call to Runtime This gives the clock time in milliseconds since starting Prolog yap flag Param Value Set or read system properties for Param argv Read only flag It unifies with a list of atoms that gives the argu ments to Yap after 74 YAP Prolog User s Manual bounded ISO Read only flag telling whether integers are bounded The value depends on whether YAP uses the GMP library or not profiling If off default do not compile call counting information for pro cedures If on compile predicates so that they calls and retries to the predicate may be counted Profiling data can be read through the call_count_data 3 built in char_conversion ISO Writable flag telling whether a character conversion tabl
142. ed by YAP get byte C ISO If C is unbound or is a character code and the current stream is a binary stream read the next byte from the current stream and unify its code with C get char C ISO If C is unbound or is an atom representation of a character and the current stream is a text stream read the next character from the current stream and unify its atom representation with C get_code C ISO If C is unbound or is the code for a character and the current stream is a text stream read the next character from the current stream and unify its code with C peek byte C ISO If C is unbound or is a character code and the current stream is a binary stream read the next byte from the current stream and unify its code with C while leaving the current stream position unaltered peek char C ISO If C is unbound or is an atom representation of a character and the current stream is a text stream read the next character from the current stream and unify its atom representation with C while leaving the current stream position unaltered peek code C ISO If C is unbound or is the code for a character and the current stream is a text stream read the next character from the current stream and unify its code with C while leaving the current stream position unaltered Skip N Skips input characters until the next occurrence of the character with ASCII code N The argument to this predicate can take the same fo
143. ees aed 145 mutex unlock all O ed AEN NEEN 146 N nb current 2 Abee setae ees 113 nb delete T za ger EIER See 114 LEE 113 nb setval 25 i does ci save pe noe noel deed da 113 no source Vater ENER Ba 20 HOG EE 28 SET E beeen tases eters 109 Daer ATOM 2 gecene quite SEA ay 34 O El EE EE 66 ONCE 15 i esti Ee Seen uE o Se quate ocd 30 P path l EE 20 21 peekzbyte 1 EE 49 peek byte 2 A os vasa wee up e etta Eaque 51 peek chaz 2 leere eri Ree PEERS 51 peek code Land 45 ve NEE de eee nitisi 49 peek c de 2 20 EE setae bons 51 profile data dE EEN EE ewe 68 profiled reset 0 bak e recreere eee 68 public 1 directive scce ceres 22 EU EE 112 put allrg 2 ue beet Prec eI ER RR EE e et 112 put byte l ni iid edad eldest RES Demi 48 ELE 50 put Chat 1 ike coheed toy RD e nere RS 48 ELE 50 puticode 1 sr ane beaded ereti e Erir 49 PUL COdE 2c ic cco ede tar d be e CERE 50 pulenv 2 cecus t ire in EDE Digi Ed 64 R EIERE MEE TT 90 ranstarb 0 cioe e veae dep DS tas eee ee 90 ranstarb 1 erd RUD UPPER adu 90 raun LD cis epp soon san en UE Raden REET 90 CD OT 93 rb clong EE 93 rb del max A NEE Eesen 92 rb delmin 4s Eege pe ges ERE 92 rb delete 3 orni is ad eats os REVERSE 92 rb delete 4 is inse mp gieren Ee 92 rb empty 1 dete ioter ERAT 92 rb sert 4 EE 92 rb keys 2 rra per redu e eed epa 93 rb lookup 3 eph ten EPR ERR an 92 rb looku pall 3 ese keeper be a ER ERES 92 rb ttap Siassssce kk ek rd eaa E ee ERE
144. efinitions required by CHR do not leak into modules where they might cause conflicts 12 4 Debugging The CHR debugging facilities are currently rather limited Only tracing is currently avail able To use the CHR debugging facilities for a CHR file it must be compiled for debugging 132 YAP Prolog User s Manual Generating debug info is controlled by the CHR option debug whose default is derived from the SWI Prolog flag generate_debug_info Therefore debug info is provided unless the nodebug is used 12 4 1 Ports For CHR constraints the four standard ports are defined call A new constraint is called and becomes active exit An active constraint exits it has either been inserted in the store after trying all rules or has been removed from the constraint store fail An active constraint fails redo An active constraint starts looking for an alternative solution In addition to the above ports CHR constraints have five additional ports wake A suspended constraint is woken and becomes active insert An active constraint has tried all rules and is suspended in the constraint store remove An active or passive constraint is removed from the constraint store if it had been inserted try An active constraints tries a rule with possibly some passive constraints The try port is entered just before committing to the rule apply An active constraints commits to a rule with possibly some passive constraints The apply port is
145. em I Yap4 3 0 test c lYap lreadline 1m You may need to adjust the libraries and library paths depending on the Operating System and your installation of Yap Note that Yap4 3 0 provides the first version of the interface The interface may change and improve in the future The following C functions are available from Yap e YAP CompileClause YAP Term Clause Compile the Prolog term Clause and assert it as the last clause for the corresponding procedure e int YAP ContinueGoal void Continue execution from the point where it stopped e void YAP Error int ID YAP Term Cause char error description Generate an YAP System Error with description given by the string error description ID is the error ID if known or 0 Cause is the term that caused the crash e void YAP Exit int exit code Exit YAP immediately The argument exit_code gives the error code and is supposed to be 0 after successful execution in Unix and Unix like systems e YAP Term YAP_GetValue Atom at Return the term value associated with the atom at If no such term exists the function will return the empty list e YAP FastInit char SavedState Initialize a copy of YAP from SavedState The copy is monolithic and currently must be loaded at the same address where it was saved YAP FastInit is a simpler version of YAP Init e YAP Init InitInfo Initialize YAP The arguments are in a C structure of type YAP_ init args The fields of InitInfo are char SavedState
146. ent for a vertice to appear in Edges vertices edges to ugraph l 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 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 vertices Graph Vertices Unify Vertices with all vertices appearing in graph Graph In the next example vertices 1 3 5 2 4 3 4 5 5 V L 1 2 3 4 5 edges Graph Edges Unify Edges with all edges appearing in graph Graph In the next example vertices 1 3 5 2 4 3 4 5 5 1 V L 1 2 3 4 5 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 add vertices 1 3 5 2 4 3 1 4 5 5 1 6 1 7 L1 8 T1 0 2 9 10 11 NG NG 0 1 3 5 2 4 3 4 5 5 6 1 T9118 L1599 D 9 D tio del vertices Vertices Graph 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 del vertices 2 1 1 3 5 2 4 3 4 51 5 1 6 1 77 2 61 8 1 ND Chapter 7 Library Predicates 105 NL 3 4 5 5 6 7 6 8 add_edges Graph Edges
147. ent with key Key and Value to the AVL tree TO creating a new AVL tree TF Duplicated elements are allowed avl_lookup Key Value T Lookup an element with key Key in the AVL tree T returning the value Value 7 4 Heaps 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 NIgN 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 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 empty heap Heap Succeeds if Heap is an empty heap 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 heap size Heap Size Reports the number of elements currently
148. ents 124 11 3 Use of unification 0 0 eee eee eee 125 11 4 Non Linear Constraints eee eee eee 125 12 CHR Constraint Handling Rules 127 12 1 Introduction cie Era hth Aere A 127 12 2 Syntax and Semantics isllisiesseseeeeelse eese 127 12 2 D ByBUBX neak cash bd ae e der epe Een beatae bones REENE E 127 12 2 2 Deman s ges dida oec pr Gea oi ade PR he de bans 128 Rule pes bl RR eere Rr HU ERR d EHPERERG eed 129 R l Name i2 diete dod EA ex dd den Se s 129 Prab up MDC 129 ET EE Ae Ae 129 12 3 CHR in YAP Proerams 0 0 0 cee cece eee eens 131 12 3 1 Embedding in Prolog Programs 131 12 3 2 Constraint declaration 0c cece eee ee eee 131 12 3 8 GCompilati Oh eic eR iri EE 131 ii iv YAP Prolog User s Manual 12 4 Debugging 0 pieh cece ene teen en see 131 TR T POTS sae ed dees ee EL DA reed ee eee et 132 1227 2 eeng Lob td o or Et ce e takes jee 132 12 4 3 CHR Debugging Predicates 00 0 ee 133 12 5 Examples i544 tesa eh Ee heroe EA OE PE URP decks 133 12 6 Compatibility with SICStus CH 134 12 7 Guidelines pree iienaa gotten TR aee e ee Re ue dn lee 134 E Ne E eetarea Soe ewe eR ET EA 137 14 Threidscsee sa tanec dad ww wwe Srace UR Re tes 139 14 1 Creating and Destroying Prolog Threads 139 14 2 Monitoring Thread 140 14 8 Thread communication 141 14 3 1 Message Queues 0 cece eee cece n 141 14
149. er to a WAM tutorial in order to understand what are the global and local stacks Yap also shows information on how many memory overflows and garbage col lections the system executed and statistics on total execution time Cputime includes all running time runtime excludes garbage collection and stack over flow time statistics Param Info Gives statistical information on the system parameter given by first argument Chapter 6 Built In Predicates 73 cputime Time since Boot Time From Last Call to Cputime This gives the total cputime in milliseconds spent executing Prolog code garbage collection and stack shifts time included garbage_collection Number of GCs Total Global Recovered Total Time Spent Number of garbage collections amount of space recovered in kbytes and total time spent doing garbage collection in milliseconds More detailed information is available using yap_flag gc_trace verbose global_stack Global Stack Used Execution Stack Free Space in kbytes currently used in the global stack and space avail able for expansion by the local and global stacks local_stack Local Stack Used Execution Stack Free Space in kbytes currently used in the local stack and space available for expansion by the local and global stacks heap Heap Used Heap Free Total space in kbytes not recoverable in backtracking It includes the program code internal data base and atom symbol table program Program Space Us
150. erating sys tem but at least the following types are supported SOCK STREAM and SOCK_ DGRAM socket DOMAIN SOCKET Call socket 4 with TYPE bound to SOCK STREAM and PROTOCOL bound to O 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 au tomatically closed when the corresponding stream is closed with close 1 or close 2 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 gt AF FILE FILENAME use file name FILENAME for UNIX or local sockets AE 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 Socket connect SOCKET PORT STREAM Interface to system call connect used for clients connect socket SOCKET to PORT The connection results in the read write stream STREAM Port information depends on the domain AF UNIX FILENAME AF FILE FILENAME connect to socket at file FILENAME AF INET HOST PORT Connect to socket at host HOST and port PORT socket listen SOCKET LENGTH Interface to system
151. ers string quoted characters escape sequence string quoted characters string quoted characters gt string character string quoted characters escape sequence gt a b r f t m w escape sequence gt 2 o escape sequence gt at_most_3_octal_digit_seq_char hi escape sequence gt x at most 2 hexa digit seq char V where string character in any character except the double quote and escape charac ters Examples SC a string a double quote The first string is an empty string the last string shows the use of double quoting The implementation of YAP represents strings as lists of integers Since Yap4 3 0 there is no static limit on string size 16 YAP Prolog User s Manual Escape sequences can be used to include the non printable characters a alert b backspace r carriage return f form feed t horizontal tabulation n new line and v vertical tabulation Escape sequences also be include the meta characters and Last one can use escape sequences to include the characters either as an octal or hexadecimal number The next examples demonstrates the use of escape sequences in YAP Deh ONUS agar 6 NC The first three examples return a list including only character 12 form feed The last example escapes the escape character Escape sequences were not available in C Prolog and in original versions of YAP up to
152. es with other code Use YapInterface h to take advantage of the new interface c interface h is still available if you cannot port the code to the new interface Access to elements in the new interface always goes through functions This includes access to the argument registers YAP_ARG1 to YAP ARG16 This change breaks code such as unify ARG1 amp t which is nowadays 1 YAP Unify ARG1 t cut_fail and cut_succeed are now functions The use of Deref is deprecated All functions that return Prolog terms including the ones that access arguments already dereferenciate their arguments Space allocated with PRESERVE_DATA is ignored by garbage collection and stack shifting As a result any pointers to a Prolog stack object including some terms may be corrupted after garbage collection or stack shifting Prolog terms should instead be stored as arguments to the backtrackable procedure Chapter 22 Using YAP as a Library 171 22 Using YAP as a Library YAP can be used as a library to be called from other programs To do so you must first create the YAP library make library make install_library This will install a file libyap a in LIBDIR and the Prolog headers in INCLUDEDIR The library contains all the functionality available in YAP except the foreign function loader and for Yap s startup routines To actually use this library you must follow a five step process 1 You must initialize the YAP environment A single functio
153. es allows using the Condor system that support High Throughput Computing HTC on large collections of distributively owned computing resources e enable tabling yes allows tabling support This option is still experimental e enable parallelism env copy sba a cow allows or parallelism supported by one of these three forms This option is still highly experimental e with gmp DIR give a path to where one can find the GMP library if not installed in the default path Next follow machine dependent details 1 2 Tuning YAP for a Particular Machine and Compiler The default options should give you best performance under GCC Although the system is tuned for this compiler we have been able to compile versions of Yap under lcc in Linux Sun s cc compiler IBM s xlc SGI s cc and Microsoft s Visual C 6 0 1 3 Tuning YAP for GCC Yap has been developed to take advantage of GCC but not to depend on it The major advantage of GCC is threaded code and explicit register reservation YAP is set by default to compile with the best compilation flags we know Even so a few specific options reduce portability The option e enable max performance yes will try to support the best available flags for a spe cific architectural model Currently the option assumes a recent version of GCC e enable debug yap compiles Yap so that it can be debugged by tools such as dbx or gdb Here follow a few hints On x86 machines the flags YAP EXTR
154. ession gt lt Expression gt maximum 11 3 Use of unification Instead of using the 1 predicate you can also use the standard unification mechanism to store constraints The following code samples are equivalent Unification with a variable X Y X Y X Y Unification with a number X 5 0 X 5 0 X 5 0 11 4 Non Linear Constraints In this version non linear constraints do not get solved until certain conditions are satisfied We call these conditions the isolation axioms They are given in the following table A B C when B or C is ground or A 5 Cor A B ANN A and B or C are ground 20 5 Cor20 B 4 A B C when C is ground or A B 3 A and B are ground 4 12 C X min Y Z when Y and Z are ground or X min 4 3 X max Y Z Y and Z are ground X max 4 3 X abs Y Y is ground X abs 7 X pow Y Z when X and Y are ground or 8 2 Z X exp Y Z X and Z are ground 8 Y 3 X Y Z Y and Z are ground X2 2 3 X 7 sin Y when X is ground or 1 sin Y X cos Y Y is ground X sin 1 5707 X tan Y 126 YAP Prolog User s Manual Chapter 12 CHR Constraint Handling Rules 127 12 CHR Constraint Handling Rules This chapter is written by Tom Schrijvers K U Leuven for the hProlog system Adjusted by Jan Wielemaker to fit the SWI Prolog documentation infrastructure and remove hProlog specific references The CHR system of SWI Prolog is t
155. etval 2 4 e mare chia eet Deda Ends 113 bssetyval 2 eene Aa id 113 between 3 eter EI rt EE Epiri 109 C call count data t ei eR ERE the 68 call count data 3 icri eben ERR gen 68 call with arps n ice pbi keari rep eitia 29 Catch us ceste date appe PUE aoe 30 EE 64 CGA resser nisor otri NBA SE E DI Seed de 109 checklist 2 eer dE tr dE E he hs ER checknodes 3 NEE EEN EEN eme ER Close static array 1 22 eres eee 71 compile 1 directive 0 2 000 19 compile ecpressions cece ee eee 20 Concat atom A Mee sage de St ck BR 109 concat atom 3 scs e ERE es cee eee Ens 109 co sulb lL dE EE ae dE EAR 19 CONVISG EE 83 copy Term Mat 2 cs ie sees res tr NNN anes 112 Current MUEI EE 146 c rrent prolog flag 2 ere erriei suier neniesa 80 current thread 2 EENS 141 D del atte ctae n RED MPUDS sie dus 112 dgraph add edges 3 0 cece eens 107 dgraph add vertices 3 0 0 000 107 dgraph complement 2 107 dgr pliucompose 3 sier KEE eese 107 dgraph del edges 3 00 e eee eens 107 derapb ed es e eee e eee 107 dorapb neighbors eese 107 dgraph neighbours eee dre eee 107 degraph mew diss bi dee 106 YAP Prolog User s Manual dgraph symmetric closure 2 107 dgraph_top_sort 2 0 0 0 eee eee eee 107 dgraph transitive closure 2 107 derapb ranspose 0c cee eee eee 107 dgraph vertices 2 ceca 107 do not com
156. f file Further reads from of the same stream may cause an error failure see open 3 read term T Options ISO Reads term T from the current input stream with execution controlled by the following options 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 syntax errors Val Control action to be taken after syntax errors See yap f1ag 2 for detailed information variable names 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 variables Names Unify Names with a list of the variables in term T Chapter 6 Built In Predicates 45 char_conversion IN OUT 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 con version from the table current_char_conversion IN 0UT ISO If IN is unbound give all current character translation
157. fragile predicate is used in a query it will be called through call cleanup 1 fragile foo 1 bar baz 2 call cleanup Goal Execute goal Goal within a cleanup context Called predicates might register cleanup Goals which are called right after the end of the call to Goal Cuts and exceptions inside Goal do not prevent the execution of the cleanup calls call cleanup might be nested call cleanup Goal CleanUpGoal This is similar to call cleanup 1 with an additional CleanUpGoal which gets called after Goal is finished 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 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 manu ally setting up cleanup contexts and registering CleanUpGoals for other than the current cleanup context Read the Source Luke 7 17 Calls With Timeout The time_out 3 command relies on the alarm 3 built in to implement a call with a maximum time of execution The command is available with the use_ module library timeo
158. g Stream Store a string in a memory buffer and output a stream that reads from this memory buffer charsio open mem write stream Stream Create a new memory buffer and output a stream that writes to it charsio peek mem write stream Stream LO L Convert the memory buffer associated with stream Stream to the difference list of character codes L LO These built ins are initialized to belong to the module charsio in init yap Novel proce dures for manipulating strings by explicitly importing these built ins YAP does not currently support opening a charsio stream in append mode or seeking in such a stream 98 YAP Prolog User s Manual 7 14 Calling The Operating System from YAP 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 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 mktime datime Year Month DayOfTheMonth Hour Minute Second
159. g the file Source code is thus compiled and main executed at the end The is useful while debugging the script as a Prolog program it guarantees that the syntax error will not propagate to the Prolog code Notice that the is required so that the shell passes the extra arguments to YAP As an example consider the following script dump_args Chapter 2 Running YAP 11 usr bin yap L tt main maint HIT write H nl maint T unix argv AllArgs maint AllArgs If you this run this script with the arguments dump args s 10000 the script will start an YAP process with stack size 10MB and the list of arguments to the process will be empty Often one wants to run the script as any other program and for this it is convenient to ignore arguments to YAP This is possible by using L as in the next version of dump args usr bin yap L main maint HIT write H n1 main T unix argv AllArgs main AllArgs DN A The indicates the next arguments are not for YAP Instead they must be sent directly to the argv built in Hence running dump_args test will write test on the standard output 12 YAP Prolog User s Manual Chapter 3 Syntax 3 Syntax We will describe the syntax of YAP at two levels We first will describe the syntax for Prolog terms In a second level we describe the tokens fro
160. goal put_atts Other frozen Fa Fb rescue conjunction put atts O0ther frozen Fa rescue the pending goal de 122 YAP Prolog User s Manual Goals n Goals Fa verify_attributes _ _ Ui 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 X22 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 cor responding verify attributes 3 predicates would typically refer to the attributes from other known solvers modules via the module prefix in Module get atts 2 Chapter 11 Constraint Logic Programming over Reals 123 11 Constraint Logic Programming over Reals YAP now uses the CLP R package developed by Leslie De Koninck K U Leuven as part of a thesis with supervisor Bart Demoen and daily advisor Tom Schrijvers and distributed with SWI Prolog This CLP R system is a port of the CLP Q R system of Sicstus Prolog and YAP by Christian Holzbaur Hol
161. h X Hyperbolic tangent asinh X Hyperbolic arc sine acosh X Hyperbolic arc cosine atanh X Hyperbolic arc tangent integer X ISO If X evaluates to a float the integer between the value of X and 0 closest to the value of X else if X evaluates to an integer the value of X float X ISO If X evaluates to an integer the corresponding float else the float itself float fractional part X ISO The fractional part of the floating point number X or 0 0 if X is an integer In the iso language mode X must be an integer float integer part X ISO The float giving the integer part of the floating point number X or X if X is an integer In the iso language mode X must be an integer abs X ISO The absolute value of X ceiling X ISO The float that is the smallest integral value not smaller than X In iso language mode the argument must be a floating point number and the result is an integer floor X ISO The float that is the greatest integral value not greater than X In iso language mode the argument must be a floating point number and the result is an integer round X ISO The nearest integral value to X If X is equidistant to two integers it will be rounded to the closest even integral value In iso language mode the argument must be a floating point number the result is an integer and it the float is equidistant it is rounded up that is to the least integer greater than X sign X ISO Return
162. h YAP to use logical update semantics dynamic 1 is a built in not a directive in YAP By default YAP fails on undefined predicates To follow default SICStus Prolog use yap flag unknown error By default directives in YAP can be called from the top level 23 2 2 Yap predicates fully compatible with SICStus Prolog These are the Prolog built ins that are fully compatible in both SICStus Prolog and YAP Chapter 23 Compatibility with Other Prolog systems 185 EE 28 d SE ele 27 lt Seed A0 Ee Ee 35 eege MG ohn cade Seer s 35 aCe RTT Tee eee eee 40 EE A0 E 36 EN Mn XOT 40 2 DPI 40 S ae ere eh DIARIAS RA Id 40 DET ER EE 36 EE 36 OSS EE 36 VE 28 COM MRNA 36 A abort c esed setae eo Ne Rei 30 absolute file name 42 add edges 9S ois esperes E 105 EE 86 add WErtiCes EE 104 ee TEE 87 EEN 34 ASSOC AG Jett cose eae ew ieee edad E 84 at end of stream 0 occse rerciriarisreviss 42 at end of stream e rerriererisirisarestskios 42 EE 32 atom codes 2 5 AE dni fett ona aes 33 EE 33 ALM COUCAL EE 33 atom to chake 2 EE 97 atom tou charg 3 cereos sl SEN okes DES 97 e sabel DE Mahe ae der tease baie alae eae 32 attribute goal 2 zii e Ret Res 119 B bbed lete 2 vs cde da ndsd br obe eerte rh 61 bb get 2 12i sen e dante Sashes bh eaten 61 Ir 61 bb2update TEE 61 break 0 g re ZE dE SEN 30 C T E E EA EAEE 64 EEN 29 callscleanup Wes t Ec PI ER da 102 call clean p 2
163. he K U Leuven CHR system The runtime environ ment is written by Christian Holzbaur and Tom Schrijvers while the compiler is written by Tom Schrijvers Both are integrated with SWI Prolog and licenced under compatible conditions with permission from the authors The main reference for SWI Prolog s CHR system is e T Schrijvers and B Demoen The K U Leuven CHR System Implementation and Application First Workshop on Constraint Handling Rules Selected Contributions Fruwirth T and Meister M eds pp 1 5 2004 12 1 Introduction Constraint Handling Rules CHR is a committed choice bottom up language embedded in Prolog It is designed for writing constraint solvers and is particularily useful for provid ing application specific constraints It has been used in many kinds of applications like scheduling model checking abduction type checking among many others CHR has previously been implemented in other Prolog systems SICStus Eclipse Yap Haskell and Java This CHR system is based on the compilation scheme and runtime environment of CHR in SICStus In this documentation we restrict ourselves to giving a short overview of CHR in general and mainly focus on elements specific to this implementation For a more thorough review of CHR we refer the reader to Freuhwirth 98 More background on CHR can be found at the CHR web site 12 2 Syntax and Semantics 12 2 1 Syntax The syntax of CHR rules in hProlog is the following
164. iable or another variable involved in one or more constraints In that case the constraint is triggered i e it becomes an active constraint and all the rules are tried Rule Types There are three different kinds of rules each with their specific semantics simplification The simplification rule removes the constraints in its head and calls its body propagation The propagation rule calls its body exactly once for the constraints in its head simpagation The simpagation rule removes the constraints in its head after the and then calls its body It is an optimization of simplification rules of the form con straints_1 constraints_2 lt gt constraints_1 body Namely in the simpagation form constraints constraints2 lt gt body constraints constraints are not called in the body Rule Names Naming a rule is optional and has no semantical meaning It only functions as documenta tion for the programmer Pragmas The semantics of the pragmas are passive Identifier The constraint in the head of a rule Identifier can only act as a passive constraint in that rule Additional pragmas may be released in the future Options It is possible to specify options that apply to all the CHR rules in the module Options are specified with the option 2 declaration option Option Value Available options are check guard bindings This option controls whether guards should be checked for illegal variable bind ings or not
165. ie abated wal es 24 module 2 directive eee cece eee eee 24 module 3 directive 000200000 24 multifile 1 directive 21 N ntu p 32 neighbors 9 sce dew EE ENEE Red ever 105 neighbo urs 3 c ceste reckon see EEN 105 REED 49 T MENO RICE 51 nodebug 0Q i ete dee echter 155 nofileerrors 0 cec i rynni inet RE peres 51 E EE 30 HOMVAR EE 32 TOSPY ege 155 E E EE 155 EG 88 EEN 88 EE 87 GUY CMM dd Eege 88 EE 32 number Cod s 2 dr ee bed ever ee 34 number to chats 2 rires o opea fond toriga 97 number touchafs 38 ora dere sta 97 nu mbervars 8 eara idm e Ra seamed EAR 34 O on eleanup 1 A ce d Gee DRE Beds 102 my 80 OPEN Bec nde asectu dese aed ba bb a gU Sd 40 open chars stream nn 97 ord add element 2 89 ord del element 3 0 000000005 89 ord disjoint 2 5 ctos te koe rure ELE Ra 89 Ofd Insert ET 89 ord ainbersect 2 iioii Ee ks uE MUS 89 ord intersect 3 co vide As cca ee dE E 89 Ord inbtersect A onc sheer NEES 89 Ord Jet Fo agoe eege terree ERES 85 ord member 22 EE dE HE Ee 89 ofd seteq 2 sacs HA cate SEA 89 ord setproduct 3 NEEN EEN treri 90 ord subtract 3 c eere re bh red 90 ord syindif 8 wi cei ice speed ee ester esas ees 90 OFA AUMION EE 90 OFd2UMION EE 90 ofd su nion 4 s eves tee ee NED HERDER 90 ortdsubsel 2 Loses edd fr Are abe eo Sch 90 P peek char ld ive dee ef eb tpe Agut 49 permutati
166. in 0 R 1 7 8 Queues The following queue manipulation routines are available once included with the use module library queues command Queues are implemented with difference lists Chapter 7 Library Predicates 91 make queue Queue Creates a new empty queue It should only be used to create a new queue join queue Element 0ldQueue NewQueue Adds the new element at the end of the queue list join queue 4List 0ldQueue NewQueue Ads the new elements at the end of the queue jump_queue Element 0ldQueue NewQueue Adds the new element at the front of the list list jump queue 4List OldQueue NewQueue Adds all the elements of List at the front of the queue head_queue Queue Head Unifies Head with the first element of the queue serve queue 0ldQueue Head NewQueue Removes the first element of the queue for service empty queue Queue Tests whether the queue is empty length queue Queue Length Counts the number of elements currently in the queue list to queue List Queue Creates a new queue with the same elements as List queue to list Queue List Creates a new list with the same elements as Queue 7 9 Random Number Generator The following random number operations are included with the use module library random command Since Yap 4 3 49 Yap uses the O Keefe public domain algorithm based on the Applied Statistics algorithm AS183 getrand Key Unify Key with a
167. in_db Read or set the size of the hash table that is used for looking up the internal data base when the key is an integer profiling If off default do not compile profiling information for procedures If on compile predicates so that they will output profiling infor mation Profiling data can be read through the profile_data 3 built in Chapter 6 Built In Predicates 77 redefine_warnings If Value is unbound tell whether warnings for procedures defined in several different files are on or off If Value is bound to on enable these warnings and if it is bound to off disable them The default for YAP is off unless we are in sicstus or iso mode single_var_warnings If Value is unbound tell whether warnings for singleton variables are on or off If Value is bound to on enable these warnings and if it is bound to off disable them The default for YAP is off unless we are in sicstus or iso mode strict_iso If Value is unbound tell whether strict ISO compatibility mode is on or off If Value is bound to on set language mode to iso and enable strict mode If Value is bound to off disable strict mode and keep the current language mode The default for YAP is off Under strict ISO prolog mode all calls to non ISO built ins generate an error Compilation of clauses that would call non ISO built ins will also generate errors Pre processing for grammar rules is also disabled Module expansion is still performed Arguably ISO
168. ine You should check the default installation path which is set to Yap in the stan dard Makefile This string will usually be expanded into c NYap by Windows The cygwin environment does not provide gmp You can fetch a dll for the gmp library from http www sf net projects mingwrep It is also possible to configure Yap to be a part of the cygwin environment In this case you should use YAP Prolog User s Manual mkdir cyg YAPSRC configure enable coroutining enable max performance VV enable cygwin yes make make install Yap will then compile using the cygwin library and will be installed in cyg win s usr local You can use Yap from a cygwin console or as a standalone application as long as it can find cygwini dll in its path 1 3 1 Compiling Under Visual C Yap compiles cleanly under Microsoft s Visual C release 6 0 We next give a step by step tutorial on how to compile Yap manually using this environment 1 First it is a good idea to build Yap as a DLL create a project named yapdll using File New The project will be a DLL project initially empty Notice that either the project is named yapdll or you must replace the prepro cessors variable YAPDLL EXPORTS to match your project names in the files YapInterface h and c_interface c add all c files in the YAPSRC C directory and in the YAPSRC OPTYap directory to the Project s Source Files use FileView add all h files in the YAPSRC H d
169. ing sub expression is chosen 3 In and constructs longer matches are chosen in preference to shorter ones 4 In sequences of expression components the components are considered from left to right In the example from above a b matches aab the ax portion of the pattern is matched first and it consumes the leading aa then the bx portion of the pattern consumes the next b Or consider the following example regexp abla 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 abla 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 bx compo nent is checked and b must match an empty string 7 12 Splay Trees 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 96 YAP Prolog User s Manual splay_access Return Key Val Tree NewTree If item Key is in tre
170. ing full installation instructions is distributed separately from yap tex Copyright 1998 2006 Paulo Moura The Pillow WEB library developed at Universidad Politecnica de Madrid by the CLIP group This package is distributed under the FSF s LGPL Documentation on this package is distributed separately from yap tex The yap2swi library implements some of the functionality of SWI s PL interface Please do refer to the SWI Prolog home page http www swi prolog org for more information on SWI Prolog and for a detailed description of its foreign inter face Chapter 1 Installing YAP 3 1 Installing YAP To compile YAP it should be sufficient to 1 2 3 E mkdir ARCH cd ARCH configure options Notice that by default configure gives you a vanilla configuration For instance in order to use coroutining and or CLP you need to do configure enable coroutining options Please see Section 1 1 Configuration Options page 3 for extra options check the Makefile for any extensions or changes you want to make YAP uses autoconf Recent versions of Yap try to follow GNU conventions on where to place software e The main executable is placed at BINDIR This executable is actually a script that calls the Prolog engine stored at LIBDIR e LIBDIR is the directory where libraries are stored YAPLIBDIR is a subdirectory that contains the Prolog engine and a Prolog library e INCLUDEDIR is used if you want to us
171. interpreter from C One must first construct a goal G and then it is sufficient to perform YAP Bool YapCallProlog YAP Term G the result will be FALSE if the goal failed or TRUE if the goal succeeded In this case the variables in G will store the values they have been unified with Execution only proceeds until finding the first solution to the goal but you can call findal1 3 or friends if you need all the solutions 21 7 Writing predicates in C We will distinguish two kinds of predicates deterministic predicates which either fail or succeed but are not backtrackable like the one in the introduction backtrackable predicates which can succeed more than once Chapter 21 C Language interface to YAP 167 The first kind of predicates should be implemented as a C function with no arguments which should return zero if the predicate fails and a non zero value otherwise The predicate should be declared to YAP in the initialization routine with a call to void YAP UserCPredicate char name YAP_Bool fn unsigned long int ar ity where name is the name of the predicate fn is the C function implementing the predicate and arity is its arity For the second kind of predicates we need two C functions The first one which is called when the predicate is first activated and the second one to be called on backtracking to provide possibly other solutions Note also that we normally also need to preserve some information to find o
172. ion i e stops Spec is either a list of ports or a predefined alias Defined aliases are full to stop at all ports none or off to never stop and default to stop at the call exit fail wake and apply ports See also leash 1 chr show store Mod Prints all suspended constraints of module Mod to the standard output This predicate is automatically called by the SWI Prolog toplevel at the end of each query for every CHR module currently loaded The prolog flag chr toplevel show store controls whether the toplevel shows the constraint stores The value true enables it Any other value disables it 12 5 Examples Here are two example constraint solvers written in CHR e The program below defines a solver with one constraint leq 2 which is a less than or equal constraint module leq cycle 3 1eq 2 use module library chr constraints leq 2 reflexivity leq X X lt gt true antisymmetry leq X Y leq Y X lt gt X Y idempotence leq X Y leq X Y lt gt true transitivity leq X Y leq Y Z gt leq X Z 134 YAP Prolog User s Manual cycle X Y 2 leq X Y leq Y 2 leq Z X e The program below implements a simple finite domain constraint solver module dom dom 2 use module library chr constraints dom 2 dom X lt gt fail dom X Y lt gt X Y dom X L1 dom X L2 lt gt intersection L1 L2 L3 dom X L3 intersection inte
173. ion is used by the compiler for various optimizations Note that it is up to the user the ensure that the mode declaration is correct with respect to the use of the constraint This option may occur once for each constraint type_declaration This option specifies the argument types for a particular constraint The value is a term with functor and arity equal to that of a constraint The arguments can be a user defined type or one of the built in types int The corresponding argument of every occurrence of the constraint is an integer number float a floating point number number a number natural a positive integer any The corresponding argument of every occurrence of the constraint can have any type This is the default value Currently type declarations are only used to improve certain optimizations guard simplification occurrence subsumption type definition This option defines a new user defined type which can be used in type declara tions The value is a term of the form type name list where name is a term and list is a list of alternatives Variables can be used to define generic types Recursive definitions are allowed Examples are Chapter 12 CHR Constraint Handling Rules 131 type bool true false type complex_number float float i type binary tree T leaf T node binary tree T binary tree T J type list D T list T The mode type declaration and
174. ion within the current constraint store This is the same as computing the supremum and equating the expression to that supremum bb_inf Ints Expression Inf Vertext Eps Computes the infimum of Expression within the current constraint store with the additional constraint that in that infimum all variables in Ints have integral values Vertex will contain the values of Ints in the infimum Eps denotes how much a value may differ from an integer to be considered an integer E g when 124 YAP Prolog User s Manual Eps 0 001 then X 4 999 will be considered as an integer 5 in this case Eps should be between 0 and 0 5 bb inf Ints Expression Inf The same as bb inf 5 but without returning the values of the integers and with an eps of 0 001 bb_inf Target Newvars CodedAnswer Returns the constraints on Target in the list CodedAnswer where all variables of Target have veen replaced by NewVars This operation does not change the constraint store E g in dump C X Y Z x y z Cons Cons will contain the constraints on X Y and Z where these variables have been replaced by atoms x y and z 11 2 Syntax of the predicate arguments The arguments of the predicates defined in the subsection above are defined in the following table Failing to meet the syntax rules will result in an exception Constraints gt lt Constraint gt W single constraint NN lt Constraint gt Constraints conjunction NN
175. irectory YAPSRONinclude directory and in the YAPSRCNOPT Yap subdirectory to the Project s Header Files Ideally you should now use m4 to generate extra h from m4 files and use configure to create a config h Or you can be lazy and fetch these files from YAPSRCNVONinclude You may want to go to Build Set Active Configuration and set Project Type to Release To use Yap s own include directories you have to set the Project option Project Project Settings C C Preprocessor Additional Include Directories to include the directories YAPSRC H YAPSRC VC include YAPSRC OPTYap and YAPSRC include The syntax is YAPSRC H YAPSRC VC include YAPSRC OPTYap YAPSRC include 7 Build the system should generate an yapdll dll and an yapdll lib 8 Copy the file yapd11 d1ll to your path The file yapd11 1ib should also be copied to L a location where the linker can find it Now you are ready to create a console interface for Yap create a second project say wyap with File New The project will be a WIN32 console project initially empty add YAPSRONconsoleNyap c to the Source Files add YAPSRC VC include config h and the files in YAPSRC include to the Header Files Chapter 1 Installing YAP 7 4 You may want to go to Build Set Active Configuration and set Project Type to Release 5 you will eventually need to bootstrap the system by booting from boot yap so write b YAPSRC p1 boot yap in Project Project Settings
176. is from 0 to but not including 33554432 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 1 term_variables Term Variables Unify Variables with a list of all variables in term Term variant Term1 Term2 Succeed if Term and Term2 are variant terms 102 YAP Prolog User s Manual subsumes Termi Term2 Succeed if Term1 subsumes Term2 Variables in term Term1 are bound so that the two terms become equal subsumes chk Termi Term2 Succeed if Term1 subsumes Term2 but does not bind any variable in Term1 variable in term Term Var Succeed if the second argument Var is a variable and occurs in term Term 7 16 Call Cleanup call cleanup 1 and call cleanup 2 allow predicates to register code for execution after the call is finished Predicates can be declared to be fragile to ensure that call cleanup is called for any Goal which needs it This library is loaded with the use module library cleanup command vo fragile P Pn Declares the predicate P module name arity as a fragile predicate module is optional default is the current typein module Whenever such a
177. keds hProlog Attributed Variables I instalation rs eta eaa ewes bade eee be EE L list manipulation 25 cal Ref reg IER M machine optimizations 00 MACTOSi RECTE 205 mutable variables E LEES 67 N PUMPA EE 14 Operating System Utilities 98 Or parallelism i isc dee ctw bes d eee eda de 147 ordered set EE NEE SE dE Sg daria 89 P e NEEN 147 prohli g EE 67 pseudo random 2 A4 eT I RR EE 90 punctuation token 0 cess eee 17 QUGU6 oe estore eee eee ea eS E es 90 91 R Red Black Trees 22222 2t Rr ebd 92 regular expressions 0 ee eee 94 Splay treege neers dade an Pena URP PCHRT ER YE 95 EE 15 String I O A ete RUE ETUR IS 96 SWIEPIOlOE IER ied eee te el ae aces 108 EE 3 13 T Fake A Auge gie AEN sume estes peas 149 timeout hessian renea debbie a Pee care eee 102 Ill 14 U undrected graphs 0 sees ee eee 108 unweighted graphs m icericcrieircereigpriais 103 updatable Tree NEES t et 103 update semantics sees es eere 184 updating terms ilh REX eee EAS 66 Utilities on terms i rule lega er E reed 101 V Variable t TR SAREEN DE ae ere HERS chews 16 206 YAP Prolog User s Manual
178. keeping e void YAP EndConsult void Finish consult mode Some observations e The system will core dump if you try to load the saved state in a different address from where it was made This may be a problem if your program uses mmap This problem will be addressed in future versions of YAP e Currently the YAP library will pollute the name space for your program e The initial library includes the complete YAP system In the future we plan to split this library into several smaller libraries e g if you do not want to perform I O e You can generate your own saved states Look at the boot yap and init yap files Chapter 23 Compatibility with Other Prolog systems 175 23 Compatibility with Other Prolog systems YAP has been designed to be as compatible as possible with other Prolog systems and initially with C Prolog More recent work on YAP has included features initially proposed for the Quintus and SICStus Prolog systems Developments since Yap4 1 6 we have striven at making YAP compatible with the ISO Prolog standard 23 1 Compatibility with the C Prolog interpreter 23 1 1 Major Differences between YAP and C Prolog YAP includes several extensions over the original C Prolog system Even so most C Prolog programs should run under YAP without changes The most important difference between YAP and C Prolog is that being YAP a compiler some changes should be made if predicates such as assert clause and retract are used
179. l name for the directory where YAP is currently consulting the file Chapter 6 Built In Predicates 81 file Full name for the file currently being consulted Notice that in cluded filed are ignored module Current source module source Full name for the file currently being read in which may be con sulted reconsulted or included stream Stream currently being read in term_position Stream position at the stream currently being read in 82 YAP Prolog User s Manual Chapter 7 Library Predicates 83 7 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 7 1 Apply Macros This library provides a set of utilities for applying a predicate to all elements of a list or to all sub terms of a term They allow to easily perform the most common do loop constructs in Prolog To avoid performance degradation due to apply 2 each call creates an equivalent Prolog program without meta calls which is executed by the Prolog engine instead Note that if the equivalent Prolog program already exists it will be simply used The library is based on code by Joachim Schimpf The following routines are available once included with the use_module library apply macros command maplist Pred ListIn ListOut Creates ListOut by applying the predicate Pred to all elements of ListIn
180. les They should be used instead Chapter 6 Built In Predicates 67 of setarg 3 as they allow the encapsulation of accesses to updatable variables Their implementation can also be more efficient for long deterministic computations setarg I S T Set the value of the Ith argument of term S to term T create_mutable D M Create new mutable variable M with initial value D get mutable D M Unify the current value of mutable term M with term D is mutable D Holds if D is a mutable term get mutable D M Unify the current value of mutable term M with term D update_mutable D M Set the current value of mutable term M to term D 6 14 Profiling Prolog Programs Predicates compiled with YAP s flag profiling set to on keep information on the number of times the predicate was called This information can be used to detect what are the most commonly called predicates in the program The YAP profiling sub system is currently under development Functionality for this sub system will increase with newer implementation Notes e Profiling works for both static and dynamic predicates e Currently only information on entries and retries to a predicate are maintained This may change in the future e As an example the following user level program gives a list of the most often called procedures in a program The procedure list profile shows all procedures irrespec tive of module and the procedure list_profile 1 shows
181. letion of a foreign language builtin Chapter 8 SWI Prolog Emulation 111 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 ips use module library oset domain X Dom var Dom get attr X domain Dom domain X List sort 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 oset_int Domain Dom2 NewDomain NewDomain gt fail NewDomain Value gt Y Value put attr Y domain NewDomain S var Y gt put_attr Y domain Domain memberchk Y Domain Before explaining the code we give some example queries domain X a b X c no domain X a b domain X a c X a domain X a b c domain X a c X DO The predicate domain 2 fetches first clause or assigns second clause the variable a domain 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
182. ling unknown 2 and that the single argument to N must be unbound In YAP the default action is to fail note that in the ISO Prolog standard the default action is error After defining undefined 1 by undefined A format Undefined predicate w n A fail and executing the goal unknown U undefined X a call to a predicate for which no clauses were defined will result in the output of a message of the form Undefined predicate user xyz A1 A2 followed by the failure of that call yap_flag unknown SPEC Alternatively one can use yap_flag 2 current prolog flag 2 or set prolog flag 2 to set this functionality In this case the first argument for the built ins should be unknown and the second argument should be either error warning fail or a goal user unknown predicate handler G M NG The user may also define clauses for user unknown predicate handler 3 hook predicate This user defined procedure is called before any system pro cessing for the undefined procedure with the first argument G set to the current 32 YAP Prolog User s Manual goal and the second M set to the current module The predicate G will be called from within the user module If user unknown_predicate_handler 3 succeeds the system will execute NG If user unknown_predicate_handler 3 fails the system will execute default action as specified by unknown 2 6 3 Predicates on terms var T ISO Succeeds if T is currently
183. ll is thrown and the handler writes Quota exhausted Execution then continues from the handler Note that in this case 100p 0 always executes until the alarm is sent Often the code you are executing succeeds or fails before the alarm is actually delivered In this case you probably want to disable the alarm when you leave the procedure The next procedure does exactly so 66 YAP Prolog User s Manual once_with_alarm Time Goal DoOnAlarm catch execute_once_with_alarm Time Goal alarm DoOnAlarm 8 execute_once_with_alarm Time Goal alarm Time alarm _ call Goal gt alarm 0 alarm _ alarm 0O alarm _ fail The procedure has three arguments the Time before the alarm is sent the Goal to execute and the goal DoOnAlarm to execute if the alarm is sent It uses catch 3 to handle the case the alarm is sent Then it starts the alarm calls the goal Goal and disables the alarm on success or failure on_signal Signal 01dAction Callable Set the interrupt handler for soft interrupt Signal to be Callable OldAction is unified with the previous handler Only a subset of the software interrupts signals can have their handlers ma nipulated through on_signal 3 Their POSIX names YAP names and default behavior is given below The YAP name of the signal is the atom that is associated with each signal and should be used as the first argument to on_ signal 3 It is chosen so that it matches the signal s POSIX name on
184. m cOnCat 3 EE 33 atom Lenet HfS orere eu rE EE Rhe EEN 33 atom to chars 2 LA BEES Ae e E 97 atom to ccharts 93 as de i e bce dare eed 97 E E EE 32 atomic con at 2 EE 33 attr unify Kho0k 2 5 e pe stale nb es 112 attribute 1 declaration ilr attribute 60al 265 reicinn pep ances ti 119 attvar 1 21212 Er t En e cide bbe eee 119 ayl insert 4 2 2 D Dev p REY Du 86 avl lookup 3 2 be Re ie Enn rw 86 B b petyal 2 2 4 pRAREeg Ser PETER betas 113 bssebval28 c e imc sciet Ne 113 E EE 62 bb delete 2 nbowa morene ve teed dee etna ae i 61 bb Bet 2 i9 cent UR RUEDA SERO S E 61 bb pit 2 nete i RA S cag AERE 61 198 bb update 3 ee dees ta ieee Ee med 61 b tween 3 een ema aeos dus 109 bounded yap f1ag 2 option 74 Break icd etu qr ew iu E Pon irs 30 al ipium p bres dd e pDIDPERPRTdS 64 NN EE 29 Gall scle anup d EE 102 call clean p 2 EE 102 Call count ebe eher E RASSE 68 Call count data 3 ged he ee eee 68 call_counting yap_flag 2 option 74 call residte 2 ee enda dE de 116 call with args ni NEE e escort hx eds 29 e DE EE 32 Cate EE 30 C N WEE 64 char_code 2 ccc cece hen 34 char conversion yap_flag 2 option 74 char conversion 2 eee 45 character escapes yap flag 2 option 74 ChOE 1 V usi Ear ek ee DE 109 checklisSt 2 i2 d vdd Mod ob EE 83 checknodeg 39 ossis DI d ERE aa 83 E Lis sspud de aed b
185. m which Prolog terms are built 3 1 Syntax of Terms Below we describe the syntax of YAP terms from the different classes of tokens defined above The formalism used will be BNF extended where necessary with attributes denoting integer precedence or operator type term subterm N term N term 0 arguments list list expr gt list tail gt subterm 1200 end of term marker term M M lt N op N fx subterm N 1 op N fy subterm N subterm N 1 op N xfx subterm N 1 subterm N 1 op N xfy subterm N subterm N op N yfx subterm N 1 subterm N 1 op N xf subterm N op N yf atom arguments subterm 1200 subterm 1200 P list string number atom variable subterm 999 subterm 999 arguments aT lr list expr subterm 999 subterm 999 list tail gt list expr subterm 999 subterm 999 14 YAP Prolog User s Manual Notes e op N T denotes an atom which has been previously declared with type T and base precedence N e Since is itself a pre declared operator with type zfy and precedence 1000 is subterm starts with a op must be followed by a space to avoid ambiguity with the case of a functor followed by arguments e g a b the same as a b of arity one versus a b the same as
186. me statistics 2 option 73 S same length 2 ANERE EE 88 GE iiis e p aes Vode c ada de bepir4 bep EY 22 save 2i isik ga dil p gg end AG PIG eeu ke 22 save program 1 visti 94 D RPVPR Gea kaw 22 save program 2 EE 22 see 1l iibioulgw s eR Vena Peed steed RE 44 seeing 1 ii blgg mes bakes HR RE PESO 44 S66n Olen cia cess s ede RET gobs ds Rd 44 SQLECE 3 ER gd Rel a weed ox reed eed 88 Selectlist 3 retrorsa pis i dee eee RER 83 serve _qUeue J ENEE RPLR EE 91 set input fl eue v iran nen icit 42 Bet Output l dg Gin favs ah E Ru en genie 42 set prolog fl Ep 2 ese RE teo 80 set stream position 2 sess 42 set value eee he 60 Setarg 3JB is genie hbtaad c bec HE abd 67 setenv 2 oo cece ene cece nee 109 ld PET 62 setrand 1l peresina na GM IIl NER Pars 92 EE ES T E dE 64 eher PP 100 She 11 1 EE 100 101 show op counters 1 sess 153 show_ops_by_group 1 04 153 show_table 1 ke be AE REE DERES 149 SIMPLE EE EE 32 single_var_warnings yap_flag 2 option 77 singletons 1 read term 2 option 44 SUME MANENTE RUE ONERE 49 EV ERREUR 51 Sheet deeg gi Sa da E ad 101 SOCEGU 2 oo dE dee es 53 Socket 4 s c s NE nirera ceded CC 53 Socket_accept 2 ae ceca bene ss 54 socket _accept 3 se escde eens NEEN seein 54 socket_bind 2 0 ccc cece cece eee eee Dd socket buffering i 54 socket close 1 cerne 53 socket connect 3
187. me Name to a compound term of name Name This built in will silently fail if the there is no static array with that name Chapter 6 Built In Predicates 71 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 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 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 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 update array Name Index Value Attribute value Value to Name Index Type restrictions must be respected for static arra
188. med and one can use the character _ to represent the variable These variables are known as anonymous vari ables Note that different occurrences of _ on the same term represent different anonymous variables 3 2 5 Punctuation Tokens Punctuation tokens consist of one of the following characters C Lda These characters are used to group terms 3 2 6 Layout Any characters with ASCII code less than or equal to 32 appearing before a token are ignored All the text appearing in a line after the character is taken to be a comment and ignored including Comments can also be inserted by using the sequence to start the comment and to finish it In the presence of any sequence of comments or layout characters the YAP parser behaves as if it had found a single blank character The end of a file also counts as a blank character for this purpose 18 YAP Prolog User s Manual Chapter 4 Loading Programs 19 4 Loading Programs 4 1 Program loading and updating consult F Adds the clauses written in file F or in the list of files F to the program In YAP consult 1 does not remove previous clauses for the procedures defined in F Moreover note that all code in YAP is compiled reconsult F Updates the program replacing the previous definitions for the predicates de fined in F F The same as consult F F The same as reconsult F Example filei file2 file3 file4 will consult filet file4 and
189. ments varies between 0 and 10 If Name is a complex term then call with args n behaves as call n call p X1 Xm Y1 Yn p X1 Xm Y1 Yn P 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 a X X is converted to a X call X if G H I ISO 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 gt 3 with the difference that it will backtrack over the test goal Consider the following small data base a 1 b a c x a 2 b b ety Execution of an if 3 query will proceed as follows if a X b Y c Z X 1 Y 7T X 1 Y 7 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 30 YAP Prolog User s Manual If you want G to be deterministic you should use if then else as it is both more efficient and more portable once G ISO Execute the goal G only once The predicate is defined by once G call G Note that cuts inside once 1 can only cut the other goals inside once 1 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
190. mputation It is not recommended to put clauses for a thread local predicate into a file as in the example below as the clause is only visible from the thread that loaded the source file All other threads start with an empty clause list thread local foo 1 foo gnat 14 4 Thread Synchronisation All internal Prolog operations are thread safe This implies two Prolog threads can operate on the same dynamic predicate without corrupting the consistency of the predicate This section deals with user level mutexes called monitors in ADA or critical sections by Mi crosoft A mutex is a MUTual EXclusive device which implies at most one thread can hold a mutex Mutexes are used to realise related updates to the Prolog database With related we refer to the situation where a transaction implies two or more changes to the Prolog database For example we have a predicate address 2 representing the address of a person and we want to change the address by retracting the old and asserting the new address Between these two operations the database is invalid this person has either no address or two addresses depending on the assert retract order Chapter 14 Threads 145 Here is how to realise a correct update initialization mutex_create addressbook change_address Id Address mutex_lock addressbook retractall address Id _ asserta address Id Address mutex_unlock addressbook mutex_create MutexId
191. my process so for my process o in the remainder of the example And could be loaded under YAP by executing the following prolog goal load foreign files my process init my predicates Note that since Yap4 3 3 you should not give the suffix for object files YAP will deduce the correct suffix from the operating system it is running under Yap4 3 3 now supports loading WIN NT DLLs Currently you must compile YAP under cygwin to create a library yap dll first You can then use this dll to create your own dlls 162 YAP Prolog User s Manual Have a look at the code in library regex to see how to create a dll under the cygwin mingw32 environment After loading that file the following prolog goal my_process_id N would unify N with the number of the process under which Yap is running Having presented a full example we will now examine in more detail the contents of the C source code file presented above The include statement is used to make available to the C source code the macros for the handling of prolog terms and also some Yap public definitions The function my_process_id is the implementation in C of the desired predicate Note that it returns an integer denoting the success of failure of the goal and also that it has no arguments even though the predicate being defined has one In fact the arguments of a prolog predicate written in C are accessed through macros defined in the include file with names YAP_ARG1 YAP_A
192. n YAP_FastInit asks for a contiguous chunk in your memory space fills it in with the data base and sets up YAP s stacks and execution registers You can use a saved space from a standard system by calling save_program 1 2 You then have to prepare a query to give to YAP A query is a Prolog term and you just have to use the same functions that are available in the C interface 3 You can then use YAP_RunGoal query to actually evaluate your query The argument is the query term query and the result is 1 if the query succeeded and 0 if it failed 4 You can use the term destructor functions to check how arguments were instantiated 5 If you want extra solutions you can use YAP_RestartGoal to obtain the next solu tion The next program shows how to use this system We assume the saved program contains two facts for the procedure b include lt stdio h gt include Yap YapInterface h int main int argc char argv i if YAP FastInit saved state YAP BOOT ERROR exit 1 if YAP RunGoal YAP MkAtomTerm YAP LookupAtom do 1 printf Success n while YAP_RestartGoal printf Success n F printf NOYn E The program first initializes YAP calls the query for the first time and succeeds and then backtracks twice The first time backtracking succeeds the second it fails and exits To compile this program it should be sufficient to do 172 YAP Prolog User s Manual cc o ex
193. n 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 to use the user defined predicate 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 user goal_expansion G M NG Yap now supports goal_expansion 3 This is an user defined procedure that is called after term expansion when compiling or asserting goals for each sub goal in a clause The first argument is bound to the goal and the second to the module under which the goal G will execute If goal_expansion 3 succeeds the new sub goal NG will replace G and will be processed in the same way If goal_expansion 3 fails the system will use the default rules 64 YAP Prolog User s Manual phrase P L R This predicate succeeds when the difference list L R is a phrase of type P phrase P L This predicate succeeds when L is a phrase of type P The same as phrase P L Both this predicate and the previous are used as a convenient way to start execution of grammar rules C S1 T 82 This predicate is used by the grammar rules compiler and is defined as OCCIBUTT HT 6 12 Access to Operating System Functionality The following built in predicates allow access to underlying Operating System functionality cd 4D Changes the current directory on UNIX environmen
194. n the counter calls_and_retries reaches 0 Next we show a simple example of how to use call counters yap_flag call_counting on user 1 1 end_of_file yap_flag call_counting yes yes catch call_count 10000 _ _ 1 call_counter format limit_exceeded n f limit exceeded yes Notice that we first compile the looping predicate 1 0 with call counting on Next we catch 3 to handle an exception when 1 0 performs more than 10000 reductions 6 16 Arrays 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 dynamic arrays are a differ ent 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 al ternative 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 array 2 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 b
195. ncy and possibly termination Hence appropriate simpagation rules should be added of the form constraint constraint lt gt true Multi headed rules Multi headed rules are executed more efficiently when the constraints share one or more variables Mode and type declarations Provide mode and type declarations to get more efficient program execution Make sure to disable debug nodebug and enable optimization 0 136 YAP Prolog User s Manual Chapter 13 Logtalk 137 13 Logtalk The Logtalk object oriented extension is available once included with the use_ module library logtalk command Note that although we load Logtalk using the use_module 1 built in predicate the system is not packaged as a module not does it use modules in its implementation Logtalk documentation is included in the Logtalk directory Be sure to read the Logtalk INSTALL file for additional instructions on how to customize your Logtalk installation to match your working environment For the latest Llogtalk news please see the URL http www logtalk org 138 YAP Prolog User s Manual Chapter 14 Threads 139 14 Threads YAP implements a SWI Prolog compatible multithreading library Like in SWI Prolog Prolog threads have their own stacks and only share the Prolog heap predicates records flags and other global non backtrackable data The package is based on the POSIX thread standard Butenhof 1997 PPT used on most popular
196. nd of the list or Pred fails In the latter case maplist 2 fails maplist Pred List1 List2 Apply Pred on all successive triples of elements from Listl and List2 Fails if Pred can not be applied to a pair See the example above 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 8 2 Forall 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 8 3 hProlog and SWI Prolog Attributed Variables Attributed variables provide a technique for extending the Prolog unification algorithm by hooking the binding of attributed variables There is little consensus in the Prolog commu nity on the exact definition and interface to attributed variables Yap Prolog traditionally implements a SICStus like interface but to enable SWI compatibility we have implemented the SWI Prolog interface identical to the one realised by Bart Demoen for hProlog Binding an attributed variable schedules a goal to be executed at the first possible op portunity In the current implementation the hooks are executed immediately after a suc cessful unification of the clause head or successful comp
197. ng all their public predicates Predi cate name clashes are resolved by asking the user about importing or not the predicate A warning is displayed when F is not a module file Chapter 5 The Module System 25 use_module F L Loads the files specified by F importing the predicates specified in the list L Predicate name clashes are resolved by asking the user about importing or not the predicate A warning is displayed when F is not a module file use_module M F L If module M has been defined import the procedures in L to the current module Otherwise load the files specified by F importing the predicates specified in the list L 5 4 Meta Predicates in Modules The module system must know whether predicates operate on goals or clauses Otherwise such predicates would call a goal in the module they were defined instead of calling it in the module they are currently executing So for instance module example a 1 a G call G The expected behavior for this procedure is to execute goal G within the current module that is within example On the other hand when executing ca11 1 the system only knows where ca11 1 was defined that is it only knows of primitives A similar problem arises for assert 1 and friends The meta predicate 1 declaration informs the system that some arguments of a pro cedure are goals clauses or clauses heads and that these arguments must be expanded to receive the current source module
198. ng to bind an attributed variable Unification will resume after this call e The user defined predicate attribute_goal 2 converts from an attribute to a goal e The user defined predicate project_attributes 2 is used from a set of variables into a set of constraints or goals One application of project_attributes 2 is in the top level where it is used to output the set of floundered constraints at the end of a query 10 1 Attribute Declarations Attributes are compound terms associated with a variable Each attribute has a name which is private 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 118 YAP Prolog User s Manual 10 2 Attribute Manipulation The attribute manipulation predicates always work as follows 1 The first argument is the unbound variable associated with attributes 2 The second argument is a list of attributes Each attribute will be a Prolog term or a
199. nion Sets Union Holds when Union is the union of the lists Sets ord_union Set1 Set2 Union Holds when Union is the union of Set1 and Set2 ord_union Set1 Set2 Union Diff Holds when Union is the union of Set1 and Set2 and Diff is the difference 7 7 Pseudo Random Number Integer Generator The following routines produce random non negative integers in the range 0 27 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 rannum I Produces a random non negative integer I whose low bits are not all that ran dom 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 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 ranstart Seed Initialize the random number generator with user defined Seed The same Seed always produces the same sequence of numbers 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
200. ns Note that all dynamic procedures are public The source directive defines all new or redefined predicates to be public Since Yap4 3 0 multifile procedures can be static or dynamic 4 3 Saving and Loading Prolog States save F Saves an image of the current state of YAP in file F From Yap4 1 3 onwards YAP saved states are executable files in the Unix ports save F 0UT Saves an image of the current state of YAP in file F From Yap4 1 3 onwards YAP saved states are executable files in the Unix ports Unify OUT with 1 when saving the file and OUT with 0 when restoring the saved state save_program F Saves an image of the current state of the YAP database in file F save_program F G Saves an image of the current state of the YAP database in file F and guarantee that execution of the restored code will start by trying goal G restore F Restores a previously saved state of YAP from file F YAP always tries to find saved states from the current directory first If it cannot it will use the environment variable YAPLIBDIR if defined or search the default library directory Chapter 5 The Module System 23 5 The Module System Module systems are quite important for the development of large applications YAP imple ments a module system compatible with the Quintus Prolog module system The YAP module system is predicate based This means a module consists of a set of predicates or procedures such that some predica
201. nt side effect concerns the use of cut In the above example some pro grammers 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 aristhoteles 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 160 YAP Prolog User s Manual 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 cla
202. number of elements in T rb keys 4 T Keys Keys is an infix visit with all keys in tree T Keys will be sorted but may be duplicate 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 Varo 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 Val 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 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 rb min T Key Value Key is the minimum key in T and is associated with Val rb max T Key Value Key is the maximal key in T and is associated with Val rb next T Key Next Value Next is the next element after Key in T and is associated with Val rb_previous T Key Previous Value Previous is the previous element after Key in T and is associated with Val list to rbtree L T T is the red black tree corresponding to the mapping in list L ord list to rbtree L T T is the red black tree corresponding to the mapping in
203. o atoms or integers The environment variable will be passed to she11 0 2 and can be requested using getenv 2 They also influence expand_file_name 2 setenv Name Value Set environment variable Name and Value should be instantiated to atoms or integers The environment variable will be passed to shel1 0 2 and can be requested using getenv 2 They also influence expand_file_name 2 term to atom Term Atom Succeeds if Atom describes a term that unifies with Term When Atom is instantiated Atom is converted and then unified with Term If Atom has no 110 YAP Prolog User s Manual valid syntax a syntax_error exception is raised Otherwise Term is written on Atom using write 1 working_directory 0ld 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 8 1 Invoking Predicates on all Members of a List All the predicates in this section call a predicate on all members of a list or until the predicate called fails The predicate is called via ca11 2 which implies common arguments can be put in front of the arguments obtained from the list s For example maplist plus 1 O 1 2 X X 1 2 3 we will phrase this as Predicate is applied on maplist Pred List Pred is applied successively on each element of List until the e
204. o be written and L with the maximum length of a list to write The setting will be used by write 1 or write 2 The default value for all arguments is 0 meaning unlimited depth and length write depth 3 5 5 yes write a b c d e f g al b c yes write 1 2 3 4 5 6 7 8 1 2 3 4 5 yes always prompt user Force the system to prompt the user even if the user input stream is not a terminal This command is useful if you want to obtain interactive control from a pipe or a socket 6 6 8 Using Sockets From Yap YAP includes a SICStus Prolog compatible socket interface This is a 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 I O built ins can be used to write on or read from sockets The following calls are available Chapter 6 Built In Predicates 53 socket DOMAIN TYPE PROTOCOL SOCKET Corresponds to the BSD system call socket Create a socket for domain DO MAIN of type TYPE and protocol PROTOCOL Both DOMAIN and TYPE should be atoms whereas PROTOCOL must be an integer The new socket object is accessible through a descriptor bound to the variable SOCKET The current implementation of YAP only accepts two socket domains AF INET and AF_UNIX Socket types depend on the underlying op
205. ocedures that is clauses for discontigous procedures may be separated by clauses from other procedures initialization G ISO The compiler will execute goals G after consulting the current file library_directory D Succeeds when D is a current library directory name Library directories are the places where files specified in the form library File are searched by the predicates consult 1 reconsult 1 use_module 1 or ensure loaded 1 22 YAP Prolog User s Manual file_search_path NAME DIRECTORY Allows writing file names as compound terms The NAME and DIRECTORY must be atoms The predicate may generate multiple solutions The predicate is originally defined as follows file_search_path library A library_directory A file_search_path system A prolog_flag host_type A Thus library A will search for a file using library_directory 1 to obtain the prefix library_directory D Succeeds when D is a current library directory name Library directories are the places where files specified in the form library File are searched by the predicates consult 1 reconsult 1 use_module 1 or ensure_loaded 1 prolog file name Name FullPath Unify FullPath with the absolute path YAP would use to consult file Name public P ISO Instructs the compiler that the source of a predicate of a list of predicates P must be kept This source is then accessible through the clause 2 procedure and through the listing family of built i
206. on Note that this option slows down execution very substantially and is only of interest to developers of the system internals or to system debuggers reset_op_counters Reinitialize all counters show_op_counters A Display the current value for the counters using label A The label must be an atom show_ops_by_group A Display the current value for the counters organized by groups using label A The label must be an atom 154 YAP Prolog User s Manual Chapter 19 Debugging 155 19 Debugging 19 1 Debugging Predicates The following predicates are available to control the debugging of programs debug debugging nodebug spy P nospy P nospyall notrace leash M Switches the debugger on Outputs status information about the debugger which includes the leash mode and the existing spy points when the debugger is on Switches the debugger off Sets spy points on all the predicates represented by P P can either be a sin gle 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 Removes spy points from all predicates specified by P The possible forms for P are the same as in spy P Removes all existing spy points Switches off the debugger and stops tracing Sets leashing mode to M The mode can be specified as
207. on 2 il leelce e RE beet e n ve 88 plirase 2 cda et LH PU rebelde ied did 64 phrase 3 iceme dies Adak oe eae EE 64 EE 100 pOpen 3 at e RE e de thawed aks 100 portraysclause 15522338 sep dew cpr seg ax RE 57 portray EE 57 pumilivell 2 d s EE Ede 32 jon MEE 46 EE 50 project_attributes 2 0 005 119 prolog filesmame 1 sees pere ig 22 prolog Has 2 Por use bre Re lees 80 prolog Joad Copntest NEE ed E 80 EE biden HEP EE 80 jin MET SEES SE ENES 48 DUG ER 50 ELE 85 ELE 118 put label EE EE 103 Q Queue Ee sese bere REY Rx RE 91 R random l islnoeeesmlec ese A RAE PSI s 91 TANEOUS RP 91 ra ds g 3 i onines ener ELE bac IU IRE YS 91 randset 3 erne rete etr eR Ret en 92 reachable 3 2 cese erem beh 106 ccn ey 44 real rer ie RI HALE Re Se cea Dk den 50 read from chars 2 9 EE or Ret eme sees 97 remove_duplicates 2 0 0 000005 88 rename EE 99 Tepedt EE 28 restore ly 1 reen were DLP RIS ede AG 22 reverse 2 hs hiding vie Mie lebyeed nt eh babs 88 S same length 2 so scrire Seege deet eee Zich 88 save program dict sas d paid REEL PUES 22 save program 2 issersenio CHER woe ee O TERA 22 Seal obe unes e EE IRURE GU Ze 44 seeing EE 44 Seen D aru escrsetieehuenr EEN 44 Jr EE 88 SELVE_QUCUE Brags s iecit pre b ed 91 set inpul Wing ds ay gene aee P RP WE ERR PERIA 42 Bet output EE 42 set stream Dostion is scsricsrioruspeseiss 42 getrand T ise it
208. onstraint and the system will try to apply the rules to it Rules are tried and executed sequentially in the order they are written A rule is conceptually tried for an active constraint in the following way The active constraint is matched with a constraint in the head of the rule If more constraints appear in the head they are looked for among the suspended constraints which are called passive constraints in this context If the necessary passive constraints can be found and all match with the head of the rule and the guard of the rule succeeds then the rule is committed and the body of the rule executed If not all the necessary passive constraint can be found the matching fails or the guard fails then the body is not executed and the process of trying and executing simply continues with the following rules If for a rule there are multiple constraints in the head the active constraint will try the rule sequentially multiple times each time trying to match with another constraint Chapter 12 CHR Constraint Handling Rules 129 This process ends either when the active constraint disappears i e it is removed by some rule or after the last rule has been processed In the latter case the active constraint becomes suspended A suspended constraint is eligible as a passive constraint for an active constraint The other way it may interact again with the rules is when a variable appearing in the con straint becomes bound to either a nonvar
209. orm 0o to represent numbers in octal base For usefulness YAP also accepts directives of the form OX to represent numbers in hexadecimal base Example the following tokens all denote the same integer 10 271010 37101 812 16 a 36 a Oxa 0012 Numbers of the form 0 a are used to represent character constants So the following tokens denote the same integer Chapter 3 Syntax 15 0 d 100 YAP version No value for VERSION supports integers that can fit the word size of the machine This is 32 bits in most current machines but 64 in some others such as the Alpha running Linux or Digital Unix The scanner will read larger or smaller integers erroneously 3 2 1 2 Floating point Numbers Floating point numbers are described by lt float gt lt digit gt lt dot gt lt digit gt lt exponent marker gt lt sign gt lt digit gt lt digit gt lt dot gt lt digit gt lt exponent marker gt lt sign gt lt digit gt 3 3 where dot denotes the decimal point character lt exponent marker gt denotes one of e or EI and sign denotes one of or Examples 10 0 10e3 10e 3 3 1415e 3 Floating point numbers are represented as a double in the target machine This is usually a 64 bit number 3 2 2 Character Strings Strings are described by the following rules string gt string quoted characters string quoted characters gt Di string quoted charact
210. os eas Up Dee pai i e gue diis 51 pet trom heap 4 i orbe ope pine ens 86 get label 3 dE 103 EE 67 get next assoc i 0c eee 85 g t prey EROEM epee cia EE 85 get value 2 si iicii cies es khan asd Meads 60 e EE 49 BEE neice tia dese OE a uses edt eee eg 50 POCCWE Age SEENEN EA 64 Betrdnd L Eege 91 global stack statistics 2 option 73 Boal expansion 3 eiri leen ee SNE dea es 63 ge TEE 34 EE 31 H WAU EE 30 halt deet boat been tte beoe ee oe 30 head_quevle 2 eee eee eee 91 heap statistics 2 option 73 h ap_Size 2 EE 86 h ap to Vist Aerer ge eae a 86 LE TEEN 20 hide predicateil eee eee ee eee 20 HOSP TG FE 99 host mname 1 3 Age gue AR Hide See AE 99 host_type yap_flag 2 option 75 I yc 29 include 1 directive cis srrrcrrriressuu 19 incore 1 ses eid see oe ee dad MERE Oana EE Y 29 index yap_flag 2 option 75 informational messages yap_flag 2 option DEER 75 initials Zation EE 80 initialization 1 directive 21 instance 2 ns eb Error rai sd urs 59 integer i i l 2224 dede teque Reed s 32 integer rounding function yap flag 2 OPE LON Pesto Shing boat whines pe 75 45 22 Ae SS Dire REP EU E Pad d E Rad 40 is assoc l uiiues waeiccueei red reu EIS 85 18 19 8t 41 252 55 0 oa eat LI ld enti d enu 8T is mutable 4 2 1050202 9 I BRNO IATS 67 is rbtree 1 t Caddie bee Boe bak he ase 92 is EE DEEN 149 J join queue 3 Ls b
211. ound The following primitives are supported 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 freeze X G Delay execution of goal G until the variable X is bound 116 YAP Prolog User s Manual frozen X G Unify G with a conjunction of goals suspended on variable X or true if no goal has suspended 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 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 2 Y Z L X Z L Y dif f 2 Y dif Z Y Y Z L X dif X 2 dif X f 2 no The system only reports one invocation of dif 2 as having suspended Chapter 10 Attributed Variables 117
212. pecific 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 Chapter 6 Built In Predicates 61 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 la
213. pile expressions 0 20 dynamic Dredicate sels 55 E eraseall ME 59 ESS EE 51 expand EE 20 F fota Eden brandene Ed deca dy 110 EEN 112 EE 112 get byte l sr nd aed ee 49 pet Ibyte 2 2 oves obi eb Ke de E renee Ae 50 cethar fT asoka neir k ae ERES 49 getchar 2 aeien e b EE TEARS 50 SetCode enges RAS 49 et code Arte 51 Set value 2 ind 2o Renee um DUM Ten g 60 getewd TIoioricibteriee Re Pese RR ERR 64 goal expansion 3 isses esee 63 prow heap 1 ole esee OR st dee ee ed 9l E EE 31 H E 20 h de predicate 1 iere beeen ia 20 I initialization 1 directive 21 18 rbtree la nic eme RR RE ERE RR UPS 92 E ETA NEE 149 K key sStatistic8 9 iae d BE eed due per RR ves 59 key st tistics 4 iei ANE danne ER Ae 59 L library directory 1 eeeee esee 21 22 list conc b 2 secte Oeo r ue etebe Ee ERES 87 list to tbtre 2 iicaiieces dete dt hehe Eni 93 Chapter 23 Compatibility with Other Prolog systems 191 M Inapargs 9 soc duvide dete Cat eene dna 83 maplist 2 24 ocio ee iro Ea er dos 110 iaphlist 9 ies tenet cer RR rro bd 83 110 Toast P eebe E rete REFERT REUS 110 imapnodes 3 sce see Ee e 83 inktime 2 see ee eg ee bee iere 98 imutex create 1 ewe ieee eek ies peed ee 145 putex_destroy lesi NEE eters e nes 145 mutex Jee BEEN ee eat 145 mutex statistics 0 2 eee eee 141 mutex trylock 1 post tenes dt eens we dree de 145 mutex unlock 1 2 2 oem b
214. play Ee Seege a ee Bie add 50 E edges 2 sure she PERS NCUCeRSRURIIES 104 empty 8s806 ME 85 empty heap gd eade ede take cest 86 empty oueue l ne 91 GE 64 99 Docs Ee Ee Ee 100 expand term 2 dee pee ude rede E 63 F EE 27 EE 2 file exists ENEE 98 le eebe Loc eese ebe Et de E EP 99 file_property 2 eroris ark eee ne 99 file search path 2 KEE EIERE scene erates 22 filleertors O oss ks errereen PANT Rd 52 ANCA Eeer tp DERE EE Hees eee 62 Atal Arve cec ion dasa ore detested deeds toa 62 Hatten Dis cesse se ete et pe RE Ae eU RESET 87 Host EE 32 flush output deg bemte rte e e 42 flushsoutput EI ore diee RUSO PURA 42 format to chars 8 scooters 96 format tochars A errore parodi EE eb aed 96 fragile soca pias Ears tee Rete Paw eR A 102 EEN 115 rozen 2 ee EE EE Rei 116 f nctor 9u ege Eege teas 34 G garbage collect 0 eee e eee dad eee 30 garbage collect atome eese 30 Seit reesi ireanii ora yep bebe IPIE eR E 30 BE sas SOS snes macht uio bp Mata cutn ds mds 85 Bet Y cie RR ERI DE HERE EE RE 49 Bel 2 obi te AR de EE M te 50 Get 88806 9 cob eer nta ta eripere beds ded 85 BEL ass OS D eL bi Ap ege Pn UE PUE eae 85 EEN 118 get trom heap 4s nae Covent iiai re e 86 Set Jabel dee RER Ser 103 get mutable 2 ret Re eee ended 67 get nexi assoG M cv eile EN Eed 85 E DEER ee cos on reder iet ge SA 85 getO 1 cimectibteepeRDRRRRS Pere bere PER 49 EE 50 getrand EE 91 ground l 2e Rb RSS EE 34 YAP Prolog User s
215. plied binding may call verify_attributes 3 Chapter 10 Attributed Variables 121 Note that the implied binding Other E1 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 ef fectively serializes the calls to verify attribute 3 Assuming that the code resides in the file domain yap we can use it via 7 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 O0ther gt 4 must be attributed then get atts ther frozen Fb has a pending
216. pty list nil or a term with functor and arity 2 last List Last True when List is a list and Last is identical to its last element list_concat Lists List True when Lists is a list of lists and List is the concatenation of Lists member Element Set True when Set is a list and Element occurs in it It may be used to test for an element or to enumerate all the elements by backtracking memberchk Element Set As member 2 but may only be used to test whether a known Element occurs in a known Set In return for this limited use it is more efficient when it is applicable nthO 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 88 YAP Prolog User s Manual nth N List Elem The same as nth0 3 except that it counts from 1 that is nth 1 H _ H nthO 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 nthO 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
217. put N but always to user_output ttyget C The same as get C but from stream user input ttyget0 C The same as getO C but from stream user input ttyskip C Like skip 1 but always using stream user input stream ttytab N The same as tab 1 but using stream user_output ttynl Outputs a new line to stream user_output 6 6 7 Controlling Input Output exists F Checks if file F exists in the current directory nofileerrors Switches off the file errors flag so that the predicates see 1 tell 1 open 3 and close 1 just fail instead of producing an error message and aborting whenever the specified file cannot be opened or closed 52 YAP Prolog User s Manual fileerrors Switches on the file_errors flag so that in certain error conditions I O predicates will produce an appropriated message and abort write_depth T L A Unifies T with the value of the maximum depth of a term to be written L with the maximum length of a list to write and A with the maximum number of arguments of a compound term to write The setting will be used by write 1 or write 2 The default value for all arguments is 0 meaning unlimited depth and length write_depth 3 5 5 yes write a b c d e f g a b c yes write 1 2 3 4 5 6 7 8 1 2 3 4 5 yes write a 1 2 3 4 5 6 7 8 a 1 2 3 4 5 yes write depth T L Same as write depth T L Unifies T with the value of the maximum depth of a term t
218. r X gt Y ISO Term X follows term Y in the standard order X gt Y ISO Term X does not precede term Y in the standard order sort L S Unifies S with the list obtained by sorting L and merging identical in the sense of elements keysort L S Assuming L is a list of the form Key Value keysort L S unifies S with the list obtained from L by sorting its elements according to the value of Key keysort 3 a 1 b 2 c 1 a 1 b S would return S 1 b 1 a 1 b 2 c 3 a length L S Unify the well defined list L with its length The procedure can be used to find the length of a pre defined list or to build a list of length S Chapter 6 Built In Predicates 6 5 Arithmetic Arithmetic expressions in YAP may use the following operators or evaluable predicates X The value of X itself X ISO Symmetric value X Y ISO Sum X Y ISO Difference X Y ISO Product X Y ISO Quotient X Y ISO Integer quotient X mod Y ISO Integer remainder X rem Y Integer remainder the same as mod exp X ISO Natural exponential log X IS0 Natural logarithm logiO X Decimal logarithm sqrt X ISO Square root sin X ISO Sine cos X ISO Cosine tan X Tangent asin X Arc sine acos X Arc cosine atan X ISO Arc tangent atan2 X Four quadrant arc tangent sinh X Hyperbolic sine cosh X Hyperbolic cosine 37 38 YAP Prolog User s Manual tan
219. r Ee 98 delete Der eg geed EE e 98 dgraph_add_edges 3 0 eee eee eee 107 dgraph add vertices 3 00 00000 107 dgraph complement 2 sess esses 107 dgraph_compose 3 torii e eese 107 derapb del edges 3 00 eee eee eee 107 dgraph del vertiees 107 dgraph_edges 2 0 00 cece eee nities 107 dgraph neighbors cece eens 107 derapb neighboura ee eeeeeee 107 deraph mew EE 106 dgraph symmetric closure 2 107 derapb top sortie 107 dgraph ransit ve closure issues 107 derapb ranspose 0c eee eee eee 107 dgraph vertices 2 25 44 ene ite ehe RES 107 EECHER 115 directory files 2 ee etiem 98 discontiguous 1 directive 21 display EEN 45 50 ek EE 50 do not compile expressions 0 20 dynamic 1 23 20 EE dE ee 55 dynamic predicate 2 lsslsellsssss 55 Chapter 23 Compatibility with Other Prolog systems 179 E EE 104 mpty asso lion aids peetae renee ed 85 empty heap 1 siecle AE 86 empty queue d xo eege dane asec pitit eriei 91 EE 64 99 eraseall 1 fia Eege ke deans ee A 59 EE 100 F false 0 centur opea et Ee Age 27 file exists WEE 98 file exists 2 erren pinares aep eee e EA E 99 file property 2 ioa reirirreiikerii itini inpia 99 file search path 2 e cose eere 22 findall 4 ces eeetepenttrtftXeetee TTE 62 flatten 2 3 Ad E r eege dE be 87 E GA EE 32 Hushzoutput esai AE peck AE EE 42 AUSH ONL P
220. r thread Prolog threads do not share data from their stacks thread_self Id Get the Prolog thread identifier of the running thread If the thread has an alias the alias name is returned thread_join Id Status Wait for the termination of thread with given Id Then unify the result status of the thread with Status After this call Id becomes invalid and all resources associated with the thread are reclaimed Note that threads with the attribute detached true cannot be joined See also current_thread 2 A thread that has been completed without thread_join 2 being called on it is partly reclaimed the Prolog stacks are released and the C thread is destroyed A small data structure representing the exit status of the thread is retained until thread_join 2 is called on the thread Defined values for Status are 140 YAP Prolog User s Manual true The goal has been proven successfully false The goal has failed exception Term The thread is terminated on an exception See print_message 2 to turn system exceptions into readable messages exited Term The thread is terminated on thread_exit 1 using the argument Term thread_detach Id Switch thread into detached state see detached option at thread_create 3 at runtime Id is the identifier of the thread placed in detached state One of the possible applications is to simplify debugging Threads that are created as detached leave no traces if they crash For not detached threads
221. racing the receiving thread 14 3 3 Threads and Dynamic Predicates Besides queues threads can share and exchange data using dynamic predicates The multi threaded version knows about two types of dynamic predicates By default a predicate declared dynamic see dynamic 1 is shared by all threads Each thread may assert retract and run the dynamic predicate Synchronisation inside Prolog guarantees the consistency of the predicate Updates are logical visible clauses are not affected by assert retract after a query started on the predicate In many cases primitive from thread synchronysation should be used to ensure application invariants on the predicate are maintained Besides shared predicates dynamic predicates can be declared with the thread 1ocal 1 directive Such predicates share their attributes but the clause list is different in each thread thread local Functor Arity related to the dynamic 1 directive It tells the system that the predicate may be modified using assert 1 retract 1 etc during execution of the program Unlike normal shared dynamic data however each thread has its own clause list for the predicate As a thread starts this clause list is empty If there are still clauses as the thread terminates these are automatically reclaimed by the system The thread local property implies the property dynamic Thread local dynamic predicates are intended for maintaining thread specific state or intermediate results of a co
222. reconsult file2 and file3 compile F In YAP the same as reconsult 1 ensure_loaded F ISO When the files specified by F are module files ensure_loaded 1 loads them if they have note been previously loaded otherwise advertises the user about the existing name clashes and prompts about importing or not those predicates Predicates which are not public remain invisible When the files are not module files ensure_loaded 1 loads them if they have not been loaded before does nothing otherwise F must be a list containing the names of the files to load include F ISO The include directive includes the text files or sequence of text files specified by F into the file being currently consulted 4 2 Changing the Compiler s Behavior This section presents a set of built ins predicates designed to set the environment for the compiler source mode 0 N The state of source mode can either be on or off When the source mode is on all clauses are kept both as compiled code and in a hidden database O is unified with the previous state and the mode is set according to N source After executing this goal YAP keeps information on the source of the predicates that will be consulted This enables the use of listing 0 listing 1 and clause 2 for those clauses The same as source mode on or as declaring all newly defined static pro cedures as public 20 YAP Prolog User s Manual no_source The opposite to source The same
223. rm and if the unification succeeds replace it by New Fail silently if no such term exists or if unification fails 6 10 Collecting Solutions to a Goal When there are several solutions to a goal if the user wants to collect all the solutions he may be led to use the data base because backtracking will forget previous solutions YAP allows the programmer to choose from several system predicates instead of writing his own routines findall 3 gives you the fastest but crudest solution The other built in predicates post process the result of the query in several different ways 62 YAP Prolog User s Manual findall T G L ISO Unifies L with a list that contains all the instantiations of the term T satisfying the goal G With the following program a 2 1 a 1 1 a 2 2 the answer to the query findall X a X Y L would be X 32 Y _33 L 2 1 2 no findall T G L LO Similar to findal1 3 but appends all answers to list LO all T G L Similar to findall T G L but eliminating repeated elements Thus assuming the same clauses as in the above example the reply to the query all X a X Y L would be X _32 Y _33 L 2 1 no bagof T G L ISO For each set of possible instances of the free variables occurring in G but not in T generates the list L of the instances of T satisfying G Again assuming the same clauses as in the examples above the reply to the query bagof X a X Y L would be
224. rms as those for put see 6 11 tab N Outputs N spaces to the current output stream nl IS0 Outputs a new line to the current output stream 50 YAP Prolog User s Manual 6 6 5 Input Output Predicates applied to Streams read S T ISO Reads term T from the stream S instead of from the current input stream read_term S T Options ISO Reads term T from stream S with execution controlled by the same options as read_term 2 write S T ISO Writes term T to stream S instead of to the current output stream write_canonical S T ISO Displays term T on the stream S Atoms are quoted when necessary and oper ators are ignored write_term S T Opts ISO Displays term T on the current output stream according to the same options used by write_term 3 writeq S T ISO As writeq 1 but the output is sent to the stream S display S T Like display 1 but using stream S to display the term print S T Prints term T to the stream S instead of to the current output stream put S N As put N but to stream S put_byte S N ISO As put byte N but to binary stream S put_char S A ISO As put char A but to text stream S put_code S N ISO As put code N but to text stream S get S C The same as get C but from stream S get0 S C The same as getO C but from stream S get byte S C ISO If C is unbound or is a character code and the stream S is a binary
225. rs database references atoms pairs lists compound terms The primitive Chapter 21 C Language interface to YAP 163 YAP_Bool YAP IsVarTerm YAP Term t returns true iff its argument is an uninstantiated variable Conversely the primitive YAP Bool YAP NonVarTerm YAP Term t returns true iff its argument is not a variable The user can create a new uninstantiated variable using the primitive YAP Term YAP MkVarTerm The following primitives can be used to discriminate among the different types of non variable terms YAP Bool YAP IsIntTerm YAP Term t YAP Bool YAP IsFloatTerm YAP Term t YAP Bool YAP IsDbRefTerm YAP Term t YAP Bool YAP IsAtomTerm YAP Term t YAP Bool YAP IsPairTerm YAP Term t YAP Bool YAP IsApplTerm YAP Term t Next we mention the primitives that allow one to destruct and construct terms All the above primitives ensure that their result is dereferenced i e that it is not a pointer to another term The following primitives are provided for creating an integer term from an integer and to access the value of an integer term YAP Term YAP MkIntTerm YAP Int i YAP Int YAP IntOfTerm YAP Term t where YAP Int is a typedef for the C integer type appropriate for the machine or compiler in question normally a long integer The size of the allowed integers is implementation dependent but is always greater or equal to 24 bits usually 32 bits on 32 bit machines and 64 on 64 bit machines The two following primiti
226. rs to Is is called after the attributed variable has been unified with a non var term possi bly 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 8 3 1 Special Purpose SWI Predicates for Attributes 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 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 put_attrs Var Attributes Set all attributes of Var See get_attrs 2 for a description of Attributes copy term nat TI TF As copy_term 2 Attributes however are not copied but replaced by fresh variables 8 4 SWI Global variables 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 Chapter 8 SWI Prolog Emulation 113 e The value
227. rsection H T L2 HI L3 member H L2 intersection T L2 L3 intersection T L2 L3 intersection T L2 L3 12 6 Compatibility with SICStus CHR There are small differences between CHR in SWI Prolog and newer YAPs and SICStus and older versions of YAP Besides differences in available options and pragmas the following differences should be noted The handler 1 declaration In SICStus every CHR module requires a handler 1 declaration declaring a unique handler name This declaration is valid syntax in SWI Prolog but will have no effect A warning will be given during compilation The rules 1 declaration In SICStus for every CHR module it is possible to only enable a subset of the available rules through the rules 1 declaration The declaration is valid syntax in SWI Prolog but has no effect A warning is given during compilation Sourcefile naming SICStus uses a two step compiler where chr files are first translated into pl files For SWI Prolog CHR rules may be defined in a file with any extension 12 7 Guidelines In this section we cover several guidelines on how to use CHR to write constraint solvers and how to do so efficiently Set semantics The CHR system allows the presence of identical constraints i e multiple constraints with the same functor arity and arguments For most constraint Chapter 12 CHR Constraint Handling Rules 135 solvers this is not desirable it affects efficie
228. rt error message sn allocate n K bytes for local and global stacks hn allocate n K bytes for heap and auxiliary stacks tn allocate n K bytes for the trail stack 1 YAP FILE compile the Prolog file YAP FILE before entering the top level L YAP FILE compile the Prolog file YAP FILE and then halt This option is useful for implementing scripts g Goal run the goal Goal before top level The goal is converted from an atom to a Prolog term z Goal run the goal Goal as top level The goal is converted from an atom to a Prolog term b BOOT FILE boot code is in Prolog file BOOT FILE The filename must define the predicate live 0 c IP HOST port connect standard streams to host IP HOST at port port filename restore state saved in the given file separator for arguments to Prolog code These arguments are visible through the unix 1 built in Note that YAP will output an error message on the following conditions e a file name was given but the file does not exist or is not a saved YAP state e the necessary amount of memory could not be allocated e the allocated memory is not enough to restore the state When restoring a saved state YAP will allocate the same amount of memory as that in use when the state was saved unless a different amount is specified by flags in the command line By default YAP restores the file startup from the current directory or from the YAP library 10 YAP Prolog User s Manual e
229. rue print message error goal failed Goal worker Id fail work Id Goal 4 Post work to be done by the pool work Id Goal thread send message Id Goal 14 3 2 Signalling Threads These predicates provide a mechanism to make another thread execute some goal as an interrupt Signalling threads is safe as these interrupts are only checked at safe points in the virtual machine Nevertheless signalling in multi threaded environments should be handled with care as the receiving thread may hold a mutex see with mutex Signalling probably only makes sense to start debugging threads and to cancel no longer needed threads with throw 1 where the receiving thread should be designed carefully do handle exceptions at any point thread signal ThreadId Goal Make thread ThreadId execute Goal at the first opportunity In the current im plementation this implies at the first pass through the Call port The predicate thread signal 2 itself places Goal into the signalled thread s signal queue and returns immediately Signals interrupts do not cooperate well with the world of multi threading mainly because the status of mutexes cannot be guaranteed easily At the call 144 YAP Prolog User s Manual port the Prolog virtual machine holds no locks and therefore the asynchronous execution is safe Goal can be any valid Prolog goal including throw 1 to make the receiving thread generate an exception and trace 0 to start t
230. s Unify Vertices with the list of neighbors of vertex Vertex in Graph If the vertice is not in the graph fail dgraph neighbours Vertex Graph Vertices Unify Vertices with the list of neighbours of vertex Vertex in Graph dgraph complement Graph NewGraph Unify NewGraph with the graph complementary to Graph 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 dgraph close Graphi Graph2 ComposedGraph Unify ComposedGraph with a new graph obtained by composing Graphl 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 dgraph transitive closure Graph Closure Unify Closure with the transitive closure of graph Graph 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 dgraph top sort Graph Vertices Unify Vertices with the topological sort of graph Graph 108 YAP Prolog User s Manual 7 21 Undirected Graphs 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 undgraph_new Graph Create a new directed graph This operation must be performed before trying to use the graph undgraph_vertice
231. s Graph Vertices Unify Vertices with all vertices appearing in graph Graph undgraph_edges Graph Edges Unify Edges with all edges appearing in graph Graph 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_del_vertices Vertices Graph 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_add_edges Graph Edges NewGraph Unify NewGraph with a new graph obtained by adding the list of edges Edges to the graph Graph 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_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 undgraph_neighbours Vertex Graph Vertices Unify Vertices with the list of neighbours of vertex Vertex in Graph undgraph_complement Graph NewGraph Unify NewGraph with the graph complementary to Graph Chapter 8 SWI Prolog Emulation 109 8 SWI Prolog Emulation This library provides a number of SWI Prolog builtins that are not by default in YAP This library is loaded with the use_module library swi command append
232. s Otherwise give the translation for IN if one exists write T ISO The term T is written to the current output stream according to the operator declarations in force display T Displays term T on the current output stream All Prolog terms are written in standard parenthesized prefix notation write_canonical T ISO Displays term T on the current output stream Atoms are quoted when neces sary and operators are ignored that is the term is written in standard paren thesized prefix notation write_term T Opts ISO Displays term T on the current output stream according to the following op tions quoted Bool If true quote atoms if this would be necessary for the atom to be recognized as an atom by YAP s parser The default value is false ignore_ops Bool If true ignore operator declarations when writing the term The default value is false numbervars Bool If true output terms of the form VAR N where N is an integer as a sequence of capital letters The default value is false portrayed Bool If true use portray 1 to portray bound terms The default value is false max_depth Depth If Depth is a positive integer use Depth as the maximum depth to portray a term The default is 0 that is unlimited depth 46 YAP Prolog User s Manual writeq T ISO print T Writes the term T quoting names to make the result acceptable to the predicate read whenever necessary
233. s va r ie Bee Meg 92 188 Sbelt t 2 Saag gad pas dE 100 chc 100 101 Deel 32 Ske ey Al dene ter Eeer SE 49 EE EE 51 SIGCD Lacon ieee Ee Eed EN sg ti 101 EE 53 EE ER socket gerept EEN ENNEN 54 socket_accept 33 EE 54 socket buid 2 285 53 socket buffering A ee peg ees 54 Sacket close Se d ees EP vete PERLES 53 socket connect 3 sseesselleessess 53 socket listen 2 coset eee tee re edere 53 socket select 5 ANEN EEN SEENEN 54 So DP 36 SPV Loses peruenit HE espace t ters 155 sireamcselect 3 i ius ottime bee heads 42 EEN 88 Dee 102 subsumes cbk 2 ac re Pepe eres 102 SO node edhe Mey fusce eds 88 gum lisb 2 92s sara eg eege A 88 sumlist 2 WEE 88 System 0 sioe ees i tepu iii ir E YU HER 101 EE EE 101 system predicate 2 0 00 005 57 T EE 49 EECH 51 EE 43 GOMES 1 chivas a wae slew p IRR RE ERES 43 berrmexpansionf2Q eink wb si aveo RE a 63 term hash 2 ido de reete e ane Set 101 term hash A eoa REESE HR E UE 101 term varlables 2 zs riaa pe E Reps 101 titrne OUb 9 EE 103 EE 100 EE 44 Vi 106 top sort 3 EE 106 transitive closure 2 lselseeseesssee 106 ir nsposel3 vc serie edited ebd es ibd 105 YAP Prolog User s Manual tree size ed EE Ae eei does dy 103 tree to ett cras eut eo tx re teh See E dee 103 Eed G ert Eech See ERE E E 27 ty Seb HERR SPRE RENEE te baa tees Ae SEE ESPEN Ee 51 EE EEN 5l Ha MC QUOND 51 i0 CP 51 tbyslap
234. scribe to the mailing list send a request to majordomo ncc up pt with body subscribe yappers Online documentation is available for YAP at http www ncc up pt vsc Yap Recent versions of Yap including both source and selected binaries can be found from this same URL This manual was written by Vitor Santos Costa Lu s Damas Rog rio Reis and Ruben Azevedo The manual is largely based on the DECsystem 10 Prolog User s Manual by D L Bowen L Byrd F C N Pereira L M Pereira and D H D Warren We have also used comments from the Edinburgh Prolog library written by R O Keefe We would also like to gratefully acknowledge the contributions from Ashwin Srinivasian We are happy to include in YAP several excellent packages developed under separate licenses Our thanks to the authors for their kind authorization to include these packages YAP Prolog User s Manual The packages are in alphabetical order The CHR package developed by Tom Schrijvers Christian Holzbaur and Jan Wiele maker The CLP R package developed Leslie De Koninck Bart Demoen Tom Schrijvers and Jan Wielemaker and based on the CLP Q R implementation by Christian Holzbauer The Logtalk Object Oriented system is developed at the University of Beira Interior Portugal by Paulo Moura The package is distributed under the Perl Artistic License Instructions about loading this package are included in this document The documen tation on this package includ
235. 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 current_input S ISO Unify S with the current input stream current_output S ISO Unify S with the current output stream at_end_of_stream ISO Succeed if the current stream has stream position end of stream or past end of stream at_end_of_stream S ISO Succeed if the stream S has stream position end of stream or past end of stream Note that S must be a readable stream set stream position S POS ISO Given a stream position POS for a stream S set the current stream position for S to be POS stream property Stream Prop ISO Obtain the properties for the open streams If the first argument is unbound the procedure will backtrack through all open streams Otherwise the first Chapter 6 Built In Predicates 43 argument must be a stream term you may use current_stream to obtain a current stream given a file name The following properties are recognized file_name P An atom giving the file name for the current stream The file names are user_input user_output and user_error for the standard streams mode P The mode used to open the file It may be one of append read or write input The stream is readable output The stream is writable alias A ISO Prolog primitive for stream aliases Yap returns one of the existing aliases for the str
236. sed to disambiguate expressions where the structure of the term denoted is not made explicit using brackets The operator of higher precedence is the main functor If there are two operators with the highest precedence the ambiguity is solved analyzing the types of the operators The possible infix types are xfx xfy yfx With an operator of type xfx both sub expressions must have lower precedence than the operator itself unless they are bracketed which assigns to them zero precedence With an operator type xfy only the left hand sub expression must have lower precedence The opposite happens for yfx type A prefix operator can be of type fx or fy and a postfix operator xf yf The meaning of the notation is analogous to the above atb c means a b c as and have the following types and precedences op 500 yfx op 400 yfx Now defining op 700 xfy op 700 xfx a b c means a b c The following is the list of the declarations of the predefined operators op 1200 fx op 1200 xfx op 1150 fx block dynamic mode public multifile meta predicate sequential table initialization op 1100 xfy 2737171 op 1050 xfy gt op 1000 xfy op 999 xfy op 900 fy not op 900 fx nospy spy op 700 xfx O gt lt lt gt lt gt gt lt b
237. sert 3 ord del element Set i Element Set2 Removing Element from Set1 returns Set2 ord disjoint Seti Set2 Holds when the two ordered sets have no element in common ord member Element Set Holds when Element is a member of Set ord insert Seti Element Set2 Inserting Element in Set1 returns Set2 It should give exactly the same result as merge Seti Element Set2 but a bit faster and certainly more clearly The same as ord add element 3 ord_intersect Set1 Set2 Holds when the two ordered sets have at least one element in common ord_intersection Seti Set2 Intersection Holds when Intersection is the ordered representation of Set1 and Set2 ord_intersection Seti Set2 Intersection Diff Holds when Intersection is the ordered representation of Set1 and Set2 Diff is the difference between Set2 and Set1 ord seteq Seti Set2 Holds when the two arguments represent the same set 90 YAP Prolog User s Manual ord_setproduct Set1 Set2 Set If Set1 and Set2 are ordered sets Product will be an ordered set of x1 x2 pairs ord subset Seti Set2 Holds when every element of the ordered set Set appears in the ordered set Set 2 ord subtract Seti Set2 Difference Holds when Difference contains all and only the elements of Set1 which are not also in Set2 ord_symdiff Set1 Set2 Difference Holds when Difference is the symmetric difference of Set1 and Set2 ord_u
238. sible by other files they can however be accessed if the module name is prefixed to the file name through the 2 operator The built in module 1 sets the current source module module M L Options Similar to module 2 this predicate defines the file where it appears as a module file it must be the first declaration in the file M must be an atom specifying the module name L must be a list containing the module s public predicates specification in the form predicate_name arity The last argument Options must be a list of options which can be filename the filename for a module to import into the current module library file a library file to import into the current module hide Opt if Opt is false keep source code for current module if true dis able module M Defines M to be the current working or type in module All files which are not binded to a module are assumed to belong to the working module also referred to as type in module To compile a non module file into a module which is not the working one prefix the file name with the module name in the form Module File when loading the file 5 3 Using Modules By default all procedures to consult a file will load the modules defined therein The two following declarations allow one to import a module explicitly They differ on whether one imports all predicate declared in the module or not use_module F Loads the files specified by F importi
239. st 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 6 9 The Blackboard YAP implements a blackboard in the style of the SICStus Prolog blackboard The black board uses the same underlying mechanism as the internal data base but has several im portant differences e t is module aware in contrast to the internal data base e Keys can only be atoms or integers and not compound terms e A single term can be stored per key e An atomic update operation is provided this is useful for parallelism bb put 4 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 bb get 4 Key Term Unify Term with a term stored in the blackboard under key Key or fail silently if no such term exists 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 bb update Key Term New Atomically unify a term stored in the blackboard under key Key with Te
240. stream This feature is not available in ISO or SICStus languages mode and is deprecated close S 0 ISO Closes the stream S following options O The only valid options are force true and force false YAP currently ignores these options 42 YAP Prolog User s Manual absolute file name Name FullPath Give the path a full path FullPath Yap would use to consult a file named Name Unify FullPath with user if the file name is user current stream F M S Defines the relation The stream S is opened on the file F in mode M It might be used to obtain all open streams by backtracking or to access the stream for a file F in mode M or to find properties for a stream S flush_output ISO Send all data in the output buffer to current output stream flush_output S ISO Send all data in the output buffer to stream S set_input S Set stream S as the current input stream Predicates like read 1 and get 1 will start using stream S set_output S Set stream S as the current output stream Predicates like write 1 and put 1 will start using stream S Stream select STREAMS TIMEOUT READSTREAMS Given a list of open STREAMS openeded 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 USECH where SECS is an integer gives the number of
241. susuusu 71 add to heap EE 86 TEE 104 alarm EE 65 DEE EES 62 always prompt user 00 cee eee eeee 52 append 9 zd ren ue Meee RE Er 87 109 178 BRGY EE A cu b aun pie ep died OR Gea alas Se 34 EE vide a te Ede edd EE 70 array element 3 AE ral assert Static ME 56 E REENEN 56 ssertz static I Fans AE vulpes Piet merde 56 ASSOC COL list 2 e eso 2a Dp tone e 84 at end ot sireamy c gelee Peer 42 at end OF Stream A ibd vien ss ae EE 42 atom chars 2s AEN beer re eter ees 33 atom codes 2 2 een ernie e ete de ess 33 atom contat 2 eesriie ie ner cowed venies 33 atom concab 8 EE 33 atom lengih 2 cu gest bbe sie eem erkene 33 atom to charg 2 ed Edge dE 97 E songs are ETSE 97 atomic concab 2 AER EE 33 attr_unity hook 20 0 EE KEE sad d 112 attribute goal 2 ak d Ee da E e EN 119 EE 119 av ingett 4 EE 86 av Jookup 9 idco ttr Fette X ette odes 86 B bzgetval 2 cetad OR ctos r bim ebbe eet 113 b setval 2 t dada hb tet bert beds bares 113 bb d lete 2 eet Rer deed 61 bb Beb 2 onere Eu EE Ee A Se H 61 EI EE 61 bb upd ate 3 ics aide ie ebe 61 b tween 3 oe arrene EIE deed yE ieai 109 C KE ae one ee RR 64 call cleanup l 988 iR RR RR SE 102 call cleanup 2 in See vp m reete 102 call count data 0 a eR LUE EES 68 call count data 8 er mere f rend 68 call residued2 d 9 dene Aere et sg ien 116 Call with arge i age eroe ne Choe A 29 callabl aire ege ege ned ed 32 Cabch d EE 30 EE EEN 64
242. systems except for MS Windows 14 1 Creating and Destroying Prolog Threads thread_create Goal Id Options Create a new Prolog thread and underlying C thread and start it by executing Goal If the thread is created succesfully the thread identifier of the created thread is unified to Id Options is a list of options Currently defined options are stack Set the limit in K Bytes to which the Prolog stacks of this thread may grow If omited the limit of the calling thread is used See also the commandline S option trail Set the limit in K Bytes to which the trail stack of this thread may grow If omited the limit of the calling thread is used See also the commandline option T alias Associate an alias name with the thread This named may be used to refer to the thread and remains valid until the thread is joined see thread_join 2 detached If false default the thread can be waited for using thread_ join 2 thread_join 2 must be called on this thread to reclaim the all resources associated to the thread If true the system will reclaim all associated resources automatically after the thread finishes Please note that thread identifiers are freed for reuse after a detached thread finishes or a normal thread has been joined See also thread_join 2 and thread_detach 1 The Goal argument is copied to the new Prolog engine This implies further instantiation of this term in either thread does not have consequences for the othe
243. tained 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 recorda K T R Makes term T the first record under key K and unifies R with its reference recordz K T R Makes term T the last record under key K and unifies R with its reference recorda_at R0 T R Makes term T the record preceding record with reference RO and unifies R with its reference recordz_at R0 T R Makes term T the record following record with reference RO and unifies R with its reference Chapter 6 Built In Predicates 59 recordaifnot K T R If a term equal to T up to variable renaming is stored under key K fail Other wise make term T the first record under key K and unify R with its reference recordzifnot K T R If a term equal to T up to variable renaming is stored under key K fail Other
244. tching the null string at the beginning of the input string matching the null string at the end of the input string a W 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 II 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 regexp RegExp String Opts Match regular expression RegExp to input string String according to options Opts The options may be e nocase Causes upper case characters in String to be treated as lower case during the matching process regexp RegExp String Opts SubMatchVars Match regular expression RegExp to input string String according to options Opts The variable SubMatchVars should be originally a list of unbound vari ables 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
245. tes are public and the others are local to a module Atoms and terms in general are global to the system Moreover the module system is flat meaning that we do not support an hierarchy of modules Modules can automatically import other modules though For compatibility with other module systems the YAP module system is non strict meaning both that there is both a way to access predicates private to a module and that is possible to declare predicates for a module from some other module YAP allows one to ignore the module system if one does not want to use it Last note that using the module system does not introduce any significant overheads only meta calls that cross module boundaries are slowed down by the presence of modules 5 1 Module Concepts The YAP module system applies to predicates All predicates belong to a module System predicates belong to the module primitives and by default new predicates belong to the module user Predicates from the module primitives are automatically visible to every module Every predicate must belong to a module This module is called its source module By default the source module for a clause occurring in a source file with a module decla ration is the declared module For goals typed in a source file without module declarations their module is the module the file is being loaded into If no module declarations exist this is the current type in module The default type in module is user but one c
246. th DEC 10 Prolog Quintus Prolog and especially with C Prolog YAP implements most of the ISO Prolog standard We are striving at full compatibil ity and the manual describes what is still missing The manual also includes a largely incomplete comparison with SICStus Prolog The document is intended neither as an introduction to Prolog nor to the implementation aspects of the compiler A good introduction to programming in Prolog is the book The Art of Prolog by L Sterling and E Shapiro published by The MIT Press Cambridge MA Other references should include the classical Programming in Prolog by W F Clocksin and C S Mellish published by Springer Verlag YAP 4 3 is known to build with many versions of gcc lt gcc 2 7 2 gt gcc 2 8 1 gt egcs 1 0 1 gcc 2 95 and on a variety of Unixen SunOS 4 1 Solaris 2 Irix 5 2 HP UX 10 Dec Alpha Unix Linux 1 2 and Linux 2 RedHat 4 0 thru 5 2 Debian 2 in both the x86 and alpha platforms It has been built on Windows NT 4 0 using Cygwin from Cygnus Solutions see README nt and using Visual C 6 0 The overall copyright and permission notice for YAP4 3 can be found in the Artistic file in this directory YAP follows the Perl Artistic license and it is thus non copylefted freeware If you have a question about this software desire to add code found a bug want to request a feature or wonder how to get further assistance please send e mail to yappersOncc up pt To sub
247. th 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 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 ge Il type regular U I size 2375 P mod_time 990826911 no make_directory Dir Create a directory Dir The name of the directory must be an atom rename_file 0ldFile NewFile Create file OldFile to NewFile This predicate uses the C built in function rename 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 host_id Id Unify Id with an identifier of the current host Yap uses
248. the status can be inspected using current_thread 2 Threads nobody is waiting for may be created normally and detach themselves just before completion This way they leave no traces on normal completion and their reason for failure can be inspected thread_exit Term Terminates the thread immediately leaving exited Term as result state for thread_join 2 If the thread has the attribute detached true it terminates but its exit status cannot be retrieved using thread_join 2 making the value of Term irrelevant The Prolog stacks and C thread are reclaimed thread at exit Term Run Goal just before releasing the thread resources This is to be compared to at halt 1 but only for the current thread These hooks are ran regardless of why the execution of the thread has been completed As these hooks are run the return code is already available through current thread 2 using the result of thread self 1 as thread identifier thread setconcurrency 0ld 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 sys tems this predicate unifies Old to 0 zero and succeeds silently 14 2 Monitoring Threads Normal multi threaded applications should not need these the predicates from this section
249. the Linux X86 and SPARC Solaris platforms Porting to other Unix like platforms should be straightforward e YapOr does not support parallel updates to the data base e YapOr does not support opening or closing of streams during parallel execution e Garbage collection and stack shifting are not supported in YapOr e 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 e YAP does not support voluntary suspension of work We expect that some of these restrictions will be removed in future releases 148 YAP Prolog User s Manual Chapter 16 Tabling 149 16 Tabling An initial cut for an implementation of tabling in the style of XSB Prolog is now available Tabling was implemented by Ricardo Rocha To experiment with tabling use DTABLING to YAP EXTRAS in the system s Makefile You can use the directive table to force calls for the argument predicate to be tabled Tabling information is stored in a trie as for XSB Prolog The following predicates may be useful to control tabled execution is_tabled PredIndicator Succeeds if the predicate PredIndicator of the form Name Arity is a tabled predicate tabling_mode PredIndicator Options Sets tabling mode options for the list or predicate given by PredIndicator The list of Options includes batched use batched scheduling for this
250. the hostid function when available 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 100 YAP Prolog User s Manual kill Id SIGNAL Send signal SIGNAL to process Id In Unix this predicate is a direct interface to kill so one can send signals to groups of processes In WIN32 the predicate is an interface to TerminateProcess so it kills Id indepent of SIGNAL 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 pid Id Unify Id with the process identifier for the current process An interface to the getpid function tmpnam File Interface with tmpnam create an unique file and unify its name with File exec Command InputStream OutputStream ErrorStream Status Exe cute command Command with its streams connected to InputStream Output Stream and ErrorStream The result for the command is returned in Status 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 1s std pipe S null P repeat getO 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
251. the procedures being used in a specific module list_profile get number of calls for each profiled procedure setof D M P D1 current_module M profile_data M P calls D profile_data output so that the most often called 4 predicates will come last write_profile_data LP list_profile Module get number of calls for each profiled procedure setof D Module P D1 profile data Module P calls D profile data Module l output so that the most often called 4 predicates will come last write profile data LP 68 YAP Prolog User s Manual write profile data write profile data D M P R ISLP 4 swap the two calls if you want the most often called predicates first format a w 32 7t d712 7t d 12 n M P D R write profile data SLP These are the current predicates to access and clear profiling data profile data Na Ar Parameter Data Give current profile data on Parameter for a predicate described by the pred icate indicator Na Ar If any of Na Ar or Parameter are unbound backtrack through all profiled predicates or stored parameters Current parameters are calls Number of times a procedure was called retries Number of times a call to the procedure was backtracked to and retried profile reset Reset all profiling information 6 15 Counting Calls Predicates compiled with YAP s flag call counting set to on update counters on the numbers of calls and of retries Counters are ac
252. the stacks and CPU time yield different values for each thread mutex statistics Print usage statistics on internal mutexes and mutexes associated with dynamic predicates For each mutex two numbers are printed the number of times the mutex was acquired and the number of collisions the number times the calling thread has to wait for the mutex The collistion count is not available on Windows as this would break portability to Windows 95 98 ME or significantly harm performance Generally collision count is close to zero on single CPU hardware 14 3 Thread communication 14 3 1 Message Queues Prolog threads can exchange data using dynamic predicates database records and other globally shared data These provide no suitable means to wait for data or a condition as they can only be checked in an expensive polling loop Message queues provide a means for threads to wait for data or conditions without using the CPU Each thread has a message queue attached to it that is identified by the thread Addi tional queues are created using message queue create 2 thread send message Queue rThreadld Term Place Term in the given queue or default queue of the indicated thread which can even be the message queue of itself see thread self 1 Any term can 142 YAP Prolog User s Manual be placed in a message queue but note that the term is copied to the receiving thread and variable bindings are thus lost This call returns immediately
253. the tree TO creating a new red black tree TF Duplicated elements are not allowed rb_lookup Key Value T Backtrack through all elements with key Key in the red black tree T returning for each the value Value rb_lookupall Key Value T Lookup all elements with key Key in the red black tree T returning the value Value rb_delete T Key TN Delete element with key Key from the tree T returning a new tree TN 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 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 T N 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 Chapter 7 Library Predicates 93 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 rb_apply T Key G TN If the value associated with key Key is Val 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 rb_visit T Pairs Pairs is an infix visit of tree T where each element of Pairs is of the form K Val rb_size T Size Size is the
254. tion of them in SWI Prolog is based on hProlog by Bart Demoen In discussion with Bart it was decided that the semantics if hProlog nb setval 2 which is equivalent to nb linkval 2 is not acceptable for normal Prolog users as the behaviour is influenced by how builtin predicates constructing terms read 1 2 etc are implemented GNU Prolog provides a rich set of global variables including arrays Arrays can be implemented easily in SWI Prolog using functor 3 and setarg 3 due to the unrestricted arity of compound terms Chapter 9 Extensions to Prolog 115 9 Extensions to Prolog YAP includes several extensions that are not enabled by default but that can be used to extend the functionality of the system These options can be set at compilation time by enabling the related compilation flag as explained in the Makefile 9 1 Rational Trees 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 rational tree Rational trees are no 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
255. trings or atoms shell1 0 Execute a new shell alarm Seconds Callable 0ldAlarm Arranges for YAP to be interrupted in Seconds seconds When interrupted YAP will execute Callable and then return to the previous execution If Seconds is 0 no new alarm is scheduled In any event any previously set alarm is canceled The variable OldAlarm unifies with the number of seconds remaining until any previously scheduled alarm was due to be delivered or with 0 if there was no previously scheduled alarm Note that execution of Callable will wait if YAP is executing built in predicates such as Input Output operations The next example shows how alarm 3 can be used to implement a simple clock loop loop ticker write flush_output get_value tick yes alarm 1 ticker _ set value tick yes alarm 1 ticker _ loop The clock ticker writes a dot and then checks the flag tick to see whether it can continue ticking If so it calls itself again Note that there is no guarantee that the each dot corresponds a second for instance if the YAP is waiting for user input ticker will wait until the user types the entry in The next example shows how alarm 3 can be used to guarantee that a certain procedure does not take longer than a certain amount of time loop loop catch alarm 10 throw ball _ loop ball format Quota exhausted n In this case after 10 seconds our loop is interrupted ba
256. ts environ E S Given an environment variable E this predicate unifies the second argument S with its value getcwd D Unify the current directory represented as an atom with the argument D putenv E S Set environment variable E to the value S If the environment variable E does not exist create a new one Both the environment variable and the value must be atoms rename F G Renames file F to G sh Creates a new shell interaction system S Passes command S to the Bourne shell on UNIX environments or the current command interpreter in WIN32 environments unix S Access to Unix like functionality argv 1 Return a list of arguments to the program These are the arguments that follow a as in the usual Unix convention cd O Change to home directory cd 1 Change to given directory Acceptable directory names are strings or atoms environ 2 If the first argument is an atom unify the second argument with the value of the corresponding environment variable getcwd 1 Unify the first argument with an atom representing the current directory Chapter 6 Built In Predicates 65 putenv 2 Set environment variable E to the value S If the environment vari able E does not exist create a new one Both the environment variable and the value must be atoms shell 1 Execute command under current shell Acceptable commands are strings or atoms system 1 Execute command with bin sh Acceptable commands are s
257. tually decreasing counters so that they can be used as timers Three counters are available e calls number of predicate calls since execution started or since system was reset e retries number of retries for predicates called since execution started or since coun ters were reset e 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 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 reset Reset call count counters All timers are also reset call count CallsMax RetriesMax CallsAndRetriesMax Set call count counter as timers YAP will generate an exception if one of the instantiated call counters decreases to 0 YAP will ignore unbound arguments e CallsMax throw the exception call counter when the counter calls reaches 0 Chapter 6 Built In Predicates 69 e RetriesMax throw the exception retry_counter when the counter retries reaches 0 e CallsAndRetriesMax throw the exception call_and_retry_counter whe
258. type definition options are provided for backward com patibility The new syntax is described below 12 3 CHR in YAP Programs 12 3 1 Embedding in Prolog Programs The CHR constraints defined in a particulary chr file are associated with a module The default module is user One should never load different chr files with the same CHR module name 12 3 2 Constraint declaration Every constraint used in CHR rules has to be declared There are two ways to do this The old style is as follows option type definition type list T Tllist D DD option mode foo 7 option type declaration foo list int float constraints foo 2 bar O The new style is as follows chr type list T gt Tllist T constraints foo 4list int float bar 12 3 3 Compilation The SWI Prolog CHR compiler exploits term expansion 2 rules to translate the constraint handling rules to plain Prolog These rules are loaded from the library chr They are activated if the compiled file has the chr extension or after finding a declaration of the format below constraints It is adviced to define CHR rules in a module file where the module declaration is immediately followed by including the chr library as examplified below module zebra zebra O use module library chr constraints Using this style CHR rules can be defined in ordinary Prolog pI files and the operator d
259. ublic 1 directive 220 te seere seksten 22 EE EE 50 pub assoG A EE 85 pub abtr 3 eae cha cel E ER RR see 112 jene Dc E 112 pul EEN 118 pub byte la c rese be Ea e E EX eg 48 put byte 2 A Ee ef SE AE bedene 50 Chapter 23 Compatibility with Other Prolog systems 181 put chaz T i 4e vehe gaiean E ret tages 48 Put chat 2 vite studies E SEENEN QUPD 50 ELTER 49 PULICOEY ere veces 50 putlabel 4e st ma ie speed geiergert EA 103 puteny EE 64 Q Queue EE 91 R random RE 91 al a ne 91 randseg 3 was geed Dee seen ND 91 T andset 3 EE 92 RE 90 EISES eas Pie CEU EE 90 EE etd tas 90 EHM 2 oua creed ey ost See argh EE dade 90 rb apply 4 ii cocos ee t hehe E REED DER pes 93 zb clote 9 obo toi RESENS geed aS 93 rb del max A AE A PRIN oir oera 92 rb del min 4c erriei eee e ERIS YS 92 rb delete 3 c ike deed AN 92 rb delete 4 iris p pep drier EE RU ERES 92 rb emply l Lesben eec e ES batt ees OPER 92 rb inseit 4 eert seen eae e E 92 EE 93 Tb IO EE 92 rb lookupall 3 eee Rb Ree E 92 rb map 2 useless nete d 93 rb gnax doiseetqeseer ra peepee nae ae cooks 93 EE 93 rboqewfL ee deeg ies See 92 Tbn Aserre taenn Made ae EE 93 rb partial map 4 Ee de pati re DEG 93 rb previous 4 iis NEE EES 93 rb se 2 eise ERR Eed ER 93 rb update 4 isse Atten e SEE RO DP Ives 93 Eb Visit DT E tor CPI oo eT SUE 93 zeachable 8 i 4 LA AE t br ERAI PE bid 106 RE iode noise ved idbecbIBP E Mee Doubs 50 read from chars 2 ese RUCePPOLOY
260. ud act mu a ak 56 a LEM epi dd 56 cleanup all 0 442 xD pee EPI 102 6C1088 15 A E su ud tute Dd hd mas 41 EE 41 close static arran l eee eee 71 COMpare 3 EE 35 e DEE 19 compile expressions 0 00 20 complement 2 mates renni rra i e E 105 COMPOSE 3 sve sr ede REV ROO PE p Y ege 106 comnpound i iore hb eue EPIS ii PSPRERP ROC 32 Concat atom 2 venes i See h ee dnos 109 concat atom 3 1 2012 BRA eec e xeEMS 109 consult 4 229 Cates ves RR EG eee es 19 convlist 3 2 2 da us d A ben Y brad 83 Copy term Eeer edu d core qoe PEERS ea 35 copy term nat 2 2 EE 112 cputime statistics 2 option 73 create mutable 2 eee eens 67 Current Aatomi er enina ed RR Yee 57 current_char_conversion 2 45 current_input 1 EE 42 current key 2 2 4322495 deep ade seieas adduct 59 current module 1 cece eee eee 72 current module cece cece eee 72 current mutex 3 eene 146 current 0p 3 a dE aie aie ee RER SC 80 current output 1 5 oder redes 42 current predicate 1 ceo es 57 current Dredicate eee eee 57 current prolog f1ag 2 2 n mee 80 YAP Prolog User s Manual current Stteam cee eee eee eee 42 current thread 2 ccc eee eee eee 141 eyclic term A DEE 101 D Gatime due x4 Mp Ves 98 db reference 16G EE 32 debug yap_flag 2 option 74 Ee EE 155 ASbugeing O EE 155 del assoc 4 ese Re SE SR 84
261. uffer buf The string including a terminating null character must fit in bufsize characters otherwise the routine will simply fail The StringToBuffer routine fails and generates an exception if String is not a valid string The C interface also includes utility routines to do the reverse that is to copy a from a buffer to a list of character codes or to a list of character atoms YAP Term YAP BufferToString char buf YAP Term YAP BufferToAtomList char buf The user provided string must include a terminating null character The C interface function calls the parser on a sequence of characters stored at buf and returns the resulting term YAP Term YAP ReadBuffer char buf YAP Term error The user provided string must include a terminating null character Syntax errors will cause returning FALSE and binding error to a Prolog term 21 4 Memory Allocation The next routine can be used to ask space from the Prolog data base void YAP AllocSpaceFromYap int size The routine returns a pointer to a buffer allocated from the code area or NULL if sufficient space was not available The space allocated with YAP_AllocSpaceFromYap can be released back to Yap by using 166 YAP Prolog User s Manual void YAP_FreeSpaceFromYap void buf The routine releases a buffer allocated from the code area The system may crash if buf is not a valid pointer to a buffer in the code area 21 5 Controlling Yap Streams from C The C Interfac
262. undgraph del edges eee 108 undgraph del vertices 3 108 ndgraph edges 225 5 pote EEG i eenei iia 108 undgraph_neighbors 3 rrrrr20 108 undgraph neighbours 3 108 Uundgr phnew 153 2 bU p eR IR RR DERI 108 undgraph vertices 2 procris rerdrebp korteri 108 nbide loc cede serne inene aera 20 unify with occurs check 35 dee pm 64 EE 31 unknown predicate handler 3 31 update aray da EE 71 update mutable 2 0 00000 67 use module EE 24 EEN 25 us module 3 eccessxe reb te E 25 V variable in term 2 oS led eme RU her RAS 102 M cDP e te oad saute 101 verife attributes 3 re scsrirrrriiosirrrreris 118 Version EE 80 versn lu uo diei secet A koren aE EREE Rap SA 80 vertices 2 baren Lode pute 104 vertices edges to ugraph 3 104 W Wa ee lee E 101 KEE 116 EE EE 145 with output to chara 97 with output to chara esses 97 with output to chara i 97 working directory 2 100 110 KEE 50 Write depth EE 52 KEE 45 KEEN 50 KEE 96 KEES 96 WEWEG te SE 50 Y yap f1ag 2 cose cece neve e rey EE we owed 73 Chapter 23 Compatibility with Other Prolog systems 183 23 1 5 Yap predicates not available in C Prolog These are C Prolog built ins not available in YAP LG The following Prolog text uses lower case letters NOLC The following Prolog text uses upper case letters only 23 2
263. ure When first found cut succeeds as a goal but if backtracking should later return to it the parent goal the one which matches the head of the clause containing the cut causing the clause activation will fail This is an extra logical predicate and cannot be explained in terms of the declarative semantics of Prolog example member X X 1 member X L member X L With the above definition member X 1 2 3 will return each element of the list by backtracking With the following defini tion member X X member X L member X L the same query would return only the first element of the list since backtracking could not pass through the cut 28 P ISO not P YAP Prolog User s Manual Goal P is not provable The execution of this predicate fails if and only if the goal P finitely succeeds It is not a true logical negation which is impossible in standard Prolog but negation by failure This predicate might be defined as P P fail NC if P did not include cuts Goal P is not provable The same as N bi This predicate is kept for compatibility with C Prolog and previous versions of YAP Uses of not 1 should be replace by 1 as YAP does not implement true negation P Q ISO Read as if then else or commit This operator is similar to the conditional operator of imperative languages and can be used alone or with an else part as follows
264. used by write 1 and friends to determine how floating point numbers are printed The default is 15g The specified value is passed to printf without further checking For example if you want less digits printed g will print all floats using 6 digits instead of the default 15 If on allow garbage collection default if off disable it Set or show the minimum free stack before starting garbage collec tion The default depends on total stack size If off default do not show information on garbage collection and stack shifts if on inform when a garbage collection or stack shift happened if verbose give detailed information on garbage collec tion and stack shifts Last if very verbose give detailed informa tion on data structures found during the garbage collection process namely on choice points Return configure system information including the machine id for which Yap was compiled and Operating System information If on allow indexing default if off disable it informational messages If on allow printing of informational messages such as the ones that are printed when consulting If off disable printing these messages It is on by default except if Yap is booted with the L flag integer rounding function ISO language Read only flag telling the rounding function used for integers Takes the value down for the current version of YAP Choose whether YAP is closer to C Prolog cprolog iso prolog iso or
265. used during debugging or after a serious execution error to return to the top level break Suspends the execution of the current goal and creates a new execution level similar to the top level displaying the following message Break level lt number gt 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 halt ISO Halts Prolog and exits to the calling application In YAP halt 0 returns the exit code 0 halt I ISO Halts Prolog and exits to the calling application returning the code given by the integer I catch Goal Exception Action 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 throw Ball 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 garbage_collect The goal garbage_collect forces a garbage collection garbage_collect_atoms The goal gar
266. uses 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 1 0 rules for noun N I N rules T N 0O rules v V I 1 0 rules for verb V I N rules T N 0 rules q Q T I 0 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 e Try to make the first argument an input argument e 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 e 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
267. ut command Chapter 7 Library Predicates time_out Goal Timeout Result 103 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 timeout This command is implemented by activating an alarm at procedure entry If the timer expires before the goal completes the alarm will through 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 Moreover time_out 3 will deac tivate 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 alarm 3 and therefore can only offer precision on the scale of seconds 7 18 Updatable Binary Trees The following queue manipulation routines are available once included with the use module library trees command get_label Index Tree Label Treats the tree as an array of N elements and returns the Index th list to tree List Tree Takes a given List of N elements and constructs a binary Tree map tree Pred OldTree NewTree Holds when OldTree and New Iree are binary trees of the same shape and Pred 01d New is true for corresponding elements of the two trees put_label Index ldTree Label Ne
268. ut the next solution In fact the role of the two functions can be better understood from the following prolog definition p start p repeat continue where start and continue correspond to the two C functions described above As an example we will consider implementing in C a predicate n100 N which when called with an instantiated argument should succeed if that argument is a numeral less or equal to 100 and when called with an uninstantiated argument should provide by backtracking all the positive integers less or equal to 100 To do that we first declare a structure which can only consist of prolog terms containing the information to be preserved on backtracking and a pointer variable to a structure of that type include YapInterface h static int start_n100 void static int continue n100 void typedef struct YAP_Term next_solution the next solution n100_data_type n100 data type n100_data We now write the C function to handle the first call static int start n100 void YAP Term t YAP_ARG1 YAP PRESERVE DATA n100 data n100 data type if YAP_IsVarTerm t n100 data gt next solution YAP_MkIntTerm 0 return continue n100 if YAP IsIntTerm t YAP IntOfTerm t O YAP_IntOfTerm t gt 100 E 168 YAP Prolog User s Manual YAP_cut_fail else YAP_cut_succeed The routine starts by getting the dereference value of the argument The call to YAP_ PRESER
269. ve 25 Min Seege pee vase renee ede ene 85 EE 89 min Of heap 3 2v ninie dr rr he 87 Min Of heater BEE Alas eect AE 87 nt 100 RUME de Ae Mr Ed ege 98 e TA 24 module 2 directive rss seere 24 module 3 directive 00 00000 24 multifile 1 directive 0 00 00 21 mutex create l A2 Ae dee E edd 145 mutex destroy les ic cries dE EEN AE 145 mutex lock 1 2c ae fib de aoe eee eS 145 mutex _statisties O SE REEL be DRE 141 mutex trylock 1 ose AE 145 mutex unlock DEE 145 mutex unlock al 0 si ioererireiirnrrinsrss 146 N Dib curr nt 2 cios eid ch eee bios ess edes Somes 113 nb delete T 23 ven ee e tt RERO de 114 nb getval 2 ess os ERR Meaty IER 113 nb setval 2 2 ieieiebL6ebepevevwere ere bred 113 Tieighbors 3 2 rise ERR dree DRE EN 105 Heighbours 3 vrccikerdaGegsas cwee ee este 105 EH 51 HOSOUTCE O SEET EES EE ER e 20 HOLE EE 30 HOspyall O 22 teen SEES DERS Age 155 Ee 88 E 88 nth recorded i dea TEE 59 EEN 87 EE 88 nthl 3 cesses e een 109 number atomj2 ie etie bre eb UR ONERE 34 number chats 2 ice tears bp PER peer ks 33 nuinber codes 2 eisegeeesbe bp AC pese IS 34 nuxber to chars 2 AER eR sence Sa 97 number Lo chare eee 97 n mberyars 9 gg bed ete te Shs en dees 34 YAP Prolog User s Manual O on cleanu p L ccce pr Rr eR Rer ER 102 on signal 8 EE 66 ONCE 1 C 30 open S cisesebnbeGAp I PRU ERRE UR Hilde n OR ed 40 OPER A quitus cse Dee L
270. verb eat active type_of_verb rest passive Chapter 21 C Language interface to YAP 21 C Language interface to YAP YAP provides the user with the necessary facilities for writing predicates in a language other than prolog Since under Unix systems most language implementations are link able to C we will describe here only the YAP interface to the C language Before describing in full detail how to interface to C code we will examine a brief example Assume the user requires a predicate my process id Id which succeeds when Id unifies with the number of the process under which YAP is running In this case we will create a my_process c file containing the C code described below include Yap YapInterface h static int my_process_id void YAP Term pid YAP_MkIntTerm getpid YAP Term out YAP_ARG1 return YAP_Unify out pid void init_my_predicates YAP UserCPredicate my process id my process id 1 s The commands to compile the above file depend on the operating system Under Linux 1386 and Alpha you should use gcc c shared fPIC my process c ld shared o my process so my process o Under Solaris2 it is sufficient to use gcc fPIC c my process c Under SunOS it is sufficient to use gcc c my process c Under Digital Unix you need to create a so file Use gcc tst c c fpic ld my process o o my process so shared expect unresolved si and replace
271. ves play a similar role for floating point terms YAP Term YAP MkFloatTerm YAP flt double YAP flt YAP FloatOfTerm YAP Term t where f1t is a typedef for the appropriate C floating point type nowadays a double The following primitives are provided for verifying whether a term is a big int creating a term from a big integer and to access the value of a big int from a term YAP Bool YAP IsBigNumTerm YAP Term t YAP Term YAP MkBigNumTerm void b void YAP BigNumOfTerm YAP Term t void b YAP must support bignum for the configuration you are using check the YAP configuration and setup For now Yap only supports the GNU GMP library and void will be a cast for mpz t Notice that YAP BigNumOfTerm requires the number to be already initialised As an example we show how to print a bignum static int p print bignum void mpz_t mz if YAP_IsBigNumTerm YAP_ARG1 164 YAP Prolog User s Manual return FALSE mpz_init mz YAP BigNumOfTerm YAP ARG1 mz gmp_printf Shows up as Zd n mz mpz clear mz return TRUE Currently no primitives are supplied to users for manipulating data base references A special typedef YAP_Atom is provided to describe prolog atoms symbolic constants The two following primitives can be used to manipulate atom terms YAP_Term YAP_MkAtomTerm YAP_Atom at YAP Atom YAP AtomOfTerm YAP Term t The following primitives are available for associating atoms with their names YAP Atom
272. wTree constructs a new tree the same shape as the old which moreover has the same elements except that the Index th one is Label tree size Tree Size Calculates the number of elements in the Tree tree to list Tree List Is the converse operation to list to tree 7 19 Unweighted Graphs 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 e 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 e 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 104 YAP Prolog User s Manual These built ins are available once included with the use_module library ugraphs command 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 suffici
273. where the variable is bound to a concrete value we simply check whether this value is in the domain Otherwise we take 112 YAP Prolog User s Manual 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 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 type error if Var is not a variable or Module is not an atom 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 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 regarless whether or not the named attribute is present attr_unify_hook AttValue VarValue Hook that must be defined in the module an attributed variable refe
274. will contain the characters that matched the next parenthesized subexpression to the right in RegExp and so on The options may be Chapter 7 Library Predicates 95 e nocase Causes upper case characters in String to be treated as lower case during the matching process e 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 al ternatives 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 1 If a regular expression could match two different parts of an input string then it will match the one that begins earliest 2 If a regular expression contains operators then the leftmost match
275. wise make term T the first record under key K and unify R with its reference 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 e K may be given in this case the built in will return all elements of the internal data base that match the key e R may be given if so returning the key and element that match the refer ence nth instance K Index T R Fetches the Indexnth entry in the internal database under the key K Entries are numbered from one If the key K are the Index are bound a reference is unified with R Otherwise the reference R must be given and the term the system will find the matching key and index 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 erased R Succeeds if the object whose database reference is R has been erased 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 eraseall K All terms belonging to the key K are erased from the internal database The predicate always succeeds current_key A K Defines the relation K is a currently defined database key whose name is the atom A
276. with functor f of arity n and using an array args of n terms with n equal to the arity of the functor YAP_MkNewApplTerm builds up a compound term whose arguments are unbound variables YAP_ArgOfTerm gives an argument to a compound term argno should be greater or equal to 1 and less or equal to the arity of the functor Chapter 21 C Language interface to YAP 165 YAP allows one to manipulate the functors of compound term The function YAP_ FunctorOfTerm allows one to obtain a variable of type YAP_Functor with the functor to aterm The following functions then allow one to construct functors and to obtain their name and arity YAP Functor YAP_MkFunctor YAP_Atom a unsigned long int arity YAP_Atom YAP_NameOfFunctor YAP_Functor f YAP_Int YAP ArityOfFunctor YAP Functor f Note that the functor is essentially a pair formed by an atom and arity 21 2 Unification YAP provides a single routine to attempt the unification of two prolog terms The routine may succeed or fail Int YAP Unify YAP Term a YAP Term b The routine attempts to unify the terms a and b returning TRUE if the unification succeeds and FALSE otherwise 21 3 Strings The YAP C interface now includes an utility routine to copy a string represented as a list of a character codes to a previously allocated buffer int YAP StringToBuffer YAP Term String char buf unsigned int bur size The routine copies the list of character codes String to a previously allocated b
277. y asso ciated 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 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 vari able 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 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 nb_getval Name Value The nb_getval 2 predicate is a synonym for b_getval 2 introduced for com patibility and symetry As most scenarios will use a particular global variable either using non backtracable or backtrackable assignment using nb_getval 2 can be used to document that the variable is used non backtracable nb_current Name Value Enumerate all defined variables with their value The order of enumeration is undefined 114 YAP Prolog User s Manual nb delete Name Delete the named global variable 8 4 1 Compatibility of SWI Prolog Global Variables Global variables have been introduced by various Prolog implementations recently The implementa
278. yap_flag 2 option 78 system Dredicate ogereressrenni tioata ps 57 tab ENEE 49 E EE 51 table statistics 1 eese 149 EAR E MEN 43 telling EE 43 term expansion 2 2 mk rere eR dee ee 63 term hash 2 eee 101 term hash 4 cece cece cece eee 101 term_to_atom 2 0 ccc eee cece eee 109 term variables 2 eee 101 thread at exit 1 esee 140 thread create 3 cee 139 thread detach 1 eee 140 thread ecit i cere 140 Predicate Index thread get message 1 lese 142 thread get message sss 142 thread join 2 dee EEN EIERE 139 thread local 1 directive 144 thread message queue create 1 142 thread message queue destroy 1 142 thread_peek_message 1 142 thread self 1 eee 139 thread_send_message 2 141 thread_setconcurrency 2 140 thread signal 2 Ais osi prem ale ELS 143 thread statistics 3 cee ee eee 141 thrOW 1 iikeca eie Ae 30 time out 3 o suceso ere aee 103 ti pnam 1 2 2 BEER DITS 100 to chars modes yap f1ag 2 option 78 E EE EE EE 44 top sO rt 2 tege dE Baile ee de dg 106 top sSOrt 9 esae EE 106 toplevel hook yap flag 2 option 78 trail statistics 2 option 73 transitive clLosure eee 106 ERHOLL es 105 tree Size6 2
279. ys This operation is available for dynamic arrays if MULTI ASSIGNMENT VARIABLES is enabled true by default Backtracking undoes up date array 3 for dynamic arrays but not for static arrays Note that update array 3 actually uses setarg 3 to update elements of dy namic 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 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 ele ments 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 6 17 Predicate Information Built ins that return information on the current predicates and modules 72 YAP Prolog User s Manual current module M Succeeds if M are defined modules A module is defined as soon as som
280. zbaur C OFAI clp q r Manual Edition 1 3 3 Austrian Research Institute for Artificial Intelligence Vienna TR 95 09 1995 http www ai univie ac at cgi bin tr online number 95 09 This port only contains the part concerning real arithmetics This manual is roughly based on the manual of the above mentioned CLP QR implementation Please note that the clpr library is not an autoload library and therefore this library must be loaded explicitely before using it use module library clpr 11 1 Solver Predicates The following predicates are provided to work with constraints Constraints Adds the constraints given by Constraints to the constraint store entailed Constraint Succeeds if Constraint is necessarily true within the current constraint store This means that adding the negation of the constraint to the store results in failure inf Expression Inf Computes the infimum of Expression within the current state of the constraint store and returns that infimum in Inf This predicate does not change the constraint store inf Expression Sup Computes the supremum of Expression within the current state of the constraint store and returns that supremum in Sup This predicate does not change the constraint store min Expression Minimizes Expression within the current constraint store This is the same as computing the infimum and equation the expression to that infimum max Expression Maximizes Express

Download Pdf Manuals

image

Related Search

Related Contents

USER MANUAL BSD-071  Phaser 340 Colour Printer Everyday Office Colour is Here!  Here - Cabrinha  Répondre aux appels d`offres  PAN 185  1 FONTE DI LUCE 150W LIGHT SOURCE 150W  print it into an PDF file  GTE 912 SE / S type and CLIPPER  Samsung RSA1DTPE Manuel de l'utilisateur  

Copyright © All rights reserved.
Failed to retrieve file