Home

YAP User`s Manual - Universidade do Porto

image

Contents

1. 0 00 005 57 T lue 50 DEER 51 RNEN 43 telling c semi e epp RM URP FEES 43 term expansion 2 ii isestee tE et tg 63 term hash 2 esset propasti ien E NETERA 97 term hask Jesruavarstanbear danske te Pez banne 97 term variableg 2 coni onroro neria redu 2 97 tinie oUt 3 EE 98 tmpnam l six pee RE EE eee Rees 96 EES 43 top sort PMMPP m 102 transitive_closure 2 usuasnuruerrerenne 102 transpose 3 cerent drag rre te aE 101 tree size usse re einer PORE ERE A 99 tree to lisU 2 ia nose hie erePE TESAREP ER PE 99 nop cm 27 tiyget 1 onis ssepe ecd eme E EE 51 TEV ECU A m 51 ttynl O cesses e ee ee eene 51 inn isse ser 51 teys kip Le iiec utet tado b Ee TROUPE 51 jtyiab EE 51 U unify with occurs check 2 35 unknown predicate handler 3 32 update mutable seses sicretoiuimesi iee 67 Uusesmodule l ecri rros ipren ee pep iaaii 24 us MOGUIE uge ig age dee nk p anes 25 use mod le 3 iu eei Rr vide net FERRO 25 V Val Ile epe orari SE NE as 32 rur m 97 verife attributes riss iccererrisscseirerri 110 KEES 80 KR EE 100 vertices edges to ugraph 3 100 W WEE EE 97 prp 107 with_output_to_chars 2 0 0 0000 93 with output to chars 93 with output Lo chara di 93 working directory 2 lesse 96 KA ES OE EE bet dE 45 Write EEE 50 WIE term aan reintra ng bode aie eg 45 Write term S ru deere ae avehed ot Be
2. Match regular expression RegExp to input string String according to options Opts The variable SubMatch Vars should be originally a list of unbound vari ables all will contain a sequence of matches that is the head of SubMatch Vars will contain the characters in String that matched the leftmost parenthesized subexpression within RegExp the next head of list will contain the characters that matched the next parenthesized subexpression to the right in RegExp and so on The options may be Chapter 7 Library Predicates 91 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 patt
3. Goals Other E1 Goals put_atts Other dom Dc Goals put atts Other dom Da Goals ord intersect Other Da 12 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 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 implied binding Chapter 11 Attributed Variables 113 X Fresh may call verify attributes 3 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 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 ye
4. In meta programming applications one needs to get a grip on the results computed by the clp Q R solver The SISCtus Prolog predicate call residue 2 provides this functionality clp r call residue 2 A B C 10 C D E A lt 10 Constraints Constraints A A lt 10 0 B B 10 0 2 0 A C D D C E 12 16 Projecting Inequalities As soon as linear inequations are involved projection gets more demanding complexity wise The current clp Q R version uses a Fourier Motzkin algorithm for the projection of linear inequalities The choice of a suitable algorithm is somewhat dependent on the number of variables to be eliminated the total number of variables and other factors It is quite easy to produce problems of moderate size where the elimination step takes some time For example when the dimension of the projection is 1 you might be better off computing the supremum and the infimum of the remaining variable instead of eliminating n 1 variables via implicit projection In order to make answers as concise as possible redundant constraints are removed by the system as well In the following set of inequalities half of them are redundant from file library clpqr examples elimination example 2 X0 X1 X2 X3 X4 1 87 X0 52 X1 27 X2 54 X3 56 X4 lt 93 33 X0 10 X1 61 X2 28 X3 29 X4 lt 63 68 X0 8 X1 35 X2 68 X3 35 X4 lt 85 90 X0 60 X1 76 X2 53 X3 24 X4 lt 68 128 YAP Pro
5. X0 2619277 17854273 X1 gt 851123 17854273 X0 6429953 16575801 X1 lt 12749681 16575801 X0 19130 1213083 X1 gt 795400 404361 X0 1251619 3956679 X17 21101146 3956679 X0 601502 4257189 X1 gt 220850 473021 Projection is quite a powerful concept that leads to surprisingly terse executable speci fications of nontrivial problems like the computation of the convex hull from a set of points in an n dimensional space Given the program 4 from file library clpqr examples elimination conv hull Points Xs lin comb Points Lambdas Zero Xs Chapter 12 CLP Q R Manual 129 zero Zero polytope Lambdas polytope Xs positive sum Xs 1 positive sum l Z Z 0 positive sum X Xs SumX X gt 0 SumX X Sum positive sum Xs Sum zero zero Z Zs Z 0 zero Zs lin_comb S1 S1 lin comb Ps Rest K Ks S1 S3 lin comb r Ps K S1 82 lin comb Rest Ks S2 S3 lin comb r 01 01 lin comb r P Ps K S Ss Kps Ss1 Kps KxP S lin_comb_r Ps K Ss Ss1 we can post the following query clp q conv hull 1 1 2 0 3 0 1 2 2 2 1 X Y Y lt 2 X 1 2 Y lt 3 X gt 1 Y gt 0 X Y gt 2 This answer is easily verified graphically 2 1 0 x 1 2 3 The convex hull program directly corresponds to the mathematical definition of t
6. 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 11 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 Domain a list of terms with Var variable can be queried for its domain by leaving Domain unbound 112 YAP Prolog User s Manual We do not present here a definition for project attributes 2 Projecting finite domain constraints happens to be difficult module domain domain 2 use module library atts use module library ordsets ord ord intersection 3 intersect 2 list to ord set 2 1 attribute dom 1 verify attributes Var Other Goals get 3 Js verify attributes _ attribute goal Var domain Var Dom get atts Var dom Da var Other gt H get atts ther dom Db gt ord intersection Da Db Dc Dc El Els Els gt s ae 4
7. 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 reader 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
8. 3 5 2 41 3 1 4 5 5 1 6 7 0 8 01 1 6 2 3 3 2 5 7 3 2 4 5 NL NL 1 2 5 61 2 3 41 3 2 4 5 5 7 6 L1 7 L1 8 11 sub 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 7 del edges 1 3 5 2 4 3 1 4 51 5 L1 6 1 7 L1 8 L1 1 6 2 3 3 2 5 7 3 2 4 5 1 3 NL NL 1 5 2 41 3 4 1 5 1 6 1 7 D1 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 0CIV I 2 In the next example transpose 1 3 5 2 4 3 4 5 5 1 5 I1 7 L1 85 LIT NL NL 1 1 2 1 3 1 1 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 1 4 1 2 7 5 5 6 7 8 1 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 neighbours 4 1 3 5 2 4 3 1 4 1 2 7 5 5 6 7 8 NL NL 1 2 7 5 complement Graph NewGraph Unify NewGraph with the graph compleme
9. 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 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 setof X a X Y L would be X _32 Y 1 L 1 2 X _32 Y 2 L 2 Chapter 6 Built In Predicates 63 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 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 e a terminal symbol may be any Prolog symbol Terminals are written as Prolog lists e an empty body is written as the empty list TI 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
10. Stm4 Stm5 lt 75 Anm6 lt 18 20 5tm3 1 UE3 X gt 0 allpos Xs We can first check whether the relaxed problem has indeed the quoted infimum clp r example flugpl Obj _ _ _ inf Obj Inf Inf 1167185 7255923203 20 5tm6 1 UE6 Computing the infimum under the additional constraints that Stm6 Stm5 Stm4 Stm3 Stm2 Anm6 Anm5 Anm4 Anm3 Anm2 Anml assume integer values at the infimum is computationally harder but the query does not change much clp r example flugpl Obj _ Ints _ bb_inf Ints Obj Inf Inf 1201500 0000000005 Chapter 12 CLP Q R Manual 135 12 22 Implementation Architecture The system consists roughly of the following components e polynomial normal form expression simplification mechanism e A solver for linear equations Holzbaur 92 e A simplex algorithm to decide linear inequalities Holzbaur 94 12 23 Fragments and Bits The internal data structure for rational numbers is rat Num Den Den is always pos itive i e the sign of the rational number is the sign of Num Further Num and Den are relative prime Note that integer N looks like rat N 1 in this representation You can control printing of terms with portray 1 Partial Evaluation Once one has a working solver it is obvious and attractive to run the constraints in a clause definition at read time or compile time and proceed with the answer constraints in place of the original constrai
11. 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 12 CLP Q R Manual 115 12 CLP Q R Manual This Manual documents a Prolog implementation of clp Q R based on SICStus featur ing extensible unification via attributed variables Edition 1 3 3 December 1995 Christian Holzbaur christian ai univie ac at Copyright 1992 1993 1994 1995 OFAI Austrian Research Institute for Artificial Intel ligence OFAI Schottengasse 3 A 1010 Vienna Austria 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 conditions 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 language under the above conditions for modified versions except that this permission notice may be stated in a translation approved by the OFAI 12 1 Introduction to CLP Q R The cIp Q R system described in this do
12. i l nE E ve PROS 55 assertz i vered eeleg es Hebei delt 55 aSSertz 2i5iL nswiepUet pO bo RU VENT dq 58 assertz Static l ig nne C Euer DEN INE 56 assoc cto DIiSt 2 2 02b beet ewe ivy 82 at end of Steam Nee eitie erao Ey 42 at end of stroam 1 1 4 ww entra 42 atom i siiisoic RR rua dede eeu vd Ed 32 atom chars 2 2c dieere eed ones 33 atom codes 2 EE 33 atom concat 2 2 bee bide d erue dus 33 atom sconcat 3 a oc duda DEEN alene 33 atom length 2 as ns er beh Ya 33 atom to Chars 2 2 bil See opaa aii at 93 atom ET ilu o I WP RE RE ERG 93 atomrc ee ee e iw dude es 32 attribute 1 declaration 109 attribute goal 2 ede xen tid ayl insert 4 0344 secede se s or pgs 83 ayl lookup 3 ice ees Zeen a E aria 83 B E EE 62 bb delete cse hn 61 Rb ed EE CR UNT ERI Un 61 bb Pit Dare adea em ERES uio 61 bb update 3 cei ERR OC REA ERES 61 bounded yap f1ag 2 option 74 break 0 aa Soke dss te ss henge ec Bh alte Setene geg puls 30 210 QI Sai ipiis qa cp add d der deg 64 Ce H ud dloleslde 4 PRI PRAES 29 call clean p 1 EE 98 call clean p 2 WEE 98 Call count deta Q0 iil oats nese awa 68 Call count data 3 22524 169 EE rg 68 call counting yap flag 2 option 74 call residue 2 i 11 4 zc Rr presa 107 call with argsS n eel ee oy dee 29 cabllable 1 beet cen sieben 32 for keel Ve SEE HEP ARE ERE UTE Ep Rd 30 edle 64 ehar COdG Aerer eg L PEST EE RA S 34 char conversion y
13. n100 data gt next solution 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 cases we use the function YAP_unify to bind the argument of the call to the value saved in n100 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 21 8 Loading Object Files The primitive predicate 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
14. treated like ordinary Prolog goals with the usual ports call exit redo fail In addition constraints may get inserted into or removed from the constraint store ports insert remove and stored constraints containing variables will be woken and reconsid ered port wake when variables are touched The execution of a constraint consists of trying to apply the rules mentioning the con straint in their heads Two ports for rules reflect this process At a try port the active constraint matches one of the heads of the rule and matching constraints for the remaining heads of the rule if any have been found as well The transition from a try port to an apply port takes place when the guard has been successfully evaluated i e when the rule commits At the apply port the body of the rule is just about to be executed The body is a Prolog goal transparent to the CHR debugger If the rule body contains CHR constraints the CHR debugger will track them again If the rules were consulted the Prolog debugger can be used to study the evaluations of the other predicates in the body 13 4 2 CHR Debugging Predicates The following predicates control the operation of the CHR debugger chr trace Switches the CHR debugger on and ensures that the next time control enters a CHR port a message will be produced and you will be asked to interact At this point you have a number of options See Section 13 4 5 CHR Debugging Options page 151 In particul
15. 2 1 2 Floating point Numbers 15 3 22 Character Strings 0 00 2 esses 15 9 2 0 EE EE Ee 16 9 2 4 Varlablegu a e ended oed rd getest cR dn 16 3 2 5 Punctuation Token 17 9 2 0 DAVOUCU psia ee testate acce Pisa ee wm Rei i 17 4 Loading PrOSgrams e6 e e Per RR RR Ra 19 4 1 Program loading and updating a snnnanaasrnnunrnrnnne 19 4 2 Changing the Compiler s Bebhavior 19 4 3 Saving and Loading Prolog States 22 5 The Module System axnn rm 23 AH Module Concepts cisci re eee eee tes re akt E 23 5 2 Defining a New Module 23 5 9 Using Modules orsi reete CR enn 24 5 4 Meta Predicates in Modules 0 0000 c ce eee eee 25 ii YAP Prolog User s Manual 6 Built In Predicates es 27 6 1 Control Predicates e gt srie 0 0 27 6 2 Handling Undefined Procedures 31 6 3 Predicates on terms assii posisi tia ia E cece een 32 6 4 Comparing Iemmzs es 35 0 5 ArIUBImeble eee rh oe eee aude beh eae armer ett 36 6 6 TO Pedersd Ode RT dde Ra 40 6 6 1 Handling Streams and les 40 6 6 2 Handling Streams and Files 43 6 6 3 Handling Input Output of Terms 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 nec 51 6 6 7 Controlling Input Output 51 6 6 8 Using So
16. 2746639193 2003059921 8174135966 8298807531 7614606680 5517027618 7093287091 4637721112 9316368892 6680331825 3012381970 7825098194 5988885193 4841984443 3043699418 7683964243 1718986106 Chapter 12 CLP Q R Manual 2904357290 9525101901 8226480016 3860626133 2744374704 5238978442 3009879312 2886939849 6841614039 5581530175 4580727386 6346324496 4914631409 7814059271 8739696552 0334295260 1573834187 8477411853 1384583000 7230696977 5056953696 7736178215 6465105820 7019837679 6717361332 6738589422 8487560233 3431738143 4563549061 1267154688 5956307381 9307021540 7423454424 7520449338 2093101416 7707854499 4249992295 9392398294 3206832823 0698112509 8792284998 6248270419 6405462531 3031072085 9570350354 3232862794 8914993488 3710753907 2656029760 9283681902 6996794686 7635148220 8879332036 7646480429 9618188159 9208680582 7862320900 5209618369 1038375051 3490763233 4167509244 7744992069 6737113200 5515108657 4454905987 8269895193 2509443117 5311802328 3041690351 5749279610 2160990235 0888707016 0115747704 125 12 13 Projection and Redundancy Elimination Once a derivation succeeds the Prolog system presents the bindings for the variables in the query In a CLP system the set of answer constraints is presented in analogy A complication in the CLP context are variables and associated constraints that were not mentioned in the query A motivating example is the famil
17. 85 Inerg J ssv nerbfer er I Rx be Le RES 86 meta predicate 1 directive 25 rt precipue e DEDE 84 numn of heap 5 Loses moo ERO ed gees aed 84 inktemp 2 gue AE per d 95 Module si exten EE Pak 24 module 2 directive 24 module 3 directive 00020 000 24 multifile 1 directive 0005 s eres 21 N utu EEE EEE 32 neighbors 3 e reet Ep ERU 101 neighbours 3 s seis deben pee IRE 101 TU MPO RM NEPOS 50 NE SEN 51 Hodebug Oeiseminieterside ba RIP REESE IO 169 nofileerrors O de gek be eese psi e e d pee 52 OSEN Oak erter ab Satin ahead at ined 30 NOUVEL T EE ES be peni ue Eee 32 hospy I ekoe deve daca det eee bU EPA 169 nospyall 0 2pueiseieherike EE Rn 169 EN SN 85 TO ER 85 nth0 2 leeden eege 85 nth0 A esses e me eene 85 Dnumber l era ee PI ante 32 number oodes 0 cee cece eee 34 number to chars 2 visae te 93 number to chars 8 NENNEN NEEN 93 numbervars 3 lssseesseeseees eee eee 34 YAP Prolog User s Manual O on leegen EE pA ERRARE REC 98 0 SVG EE Sea tH due gh EE ede idus 79 E o PR OPPPPA RETO fer neds 40 open charg stream sess 93 ord add element 2 86 ord del element 3 lsesseesseeeue 86 EE GENEE 86 te Sauda st tee le Se ERAS 87 ord intersect 2 oo cede ie ete et ER b ern 87 ord intersect 3 x cora eio cave sete REFER 87 ord list to s806 2 restarte ee tr RUE A 83 ord member 2 onecbteU PREIS bedere
18. 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 yappers ncc up pt To subscribe 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 e The CHR package developed at TUM by Ludwig Maximilians Universitaet Muenchen LMU by Dr Fruehwirth Thom and by Dr Christian Holzbaur The package is distributed under license from LMU Ludwig Maximilians University Munich Ger many Permission is granted to copy and
19. DI 35 create mutable 2 EELER EENS e E 67 current char conversion 2 45 current input l sessi tes er ER deor ts 42 Current EE 59 current module 1 hospice REENEN nel 72 Current module 2 ne prebuit pr b EE 72 current op 9 aerea dere re n m kd 79 current ott dee ENEE EEN 42 current Dredicate rererrrer oreiro n erias 57 Current Drolog Hag e eee ee eee 79 current streamt Boiss sepe ad e es hane ots 42 Gyclie Serm AL oui eren pre vas T E O V PREIS 97 D datime 1 geed E EE EE 94 del vertices 3 Lese etre EE eee 100 delete 8 NE 84 89 delete file 1 enee Ee eter eger 94 delete file 2 SEENEN reste be ER sikt ER 94 QE MN NER M 107 directory files 2 ocio c recber ree PR eR 94 discontiguous 1 directive 21 display EE 45 50 display 2 oi reete EIE ei uaga 50 do not compile expressions 0 20 dynamie l iiude enel Pee eve br ed 54 dynamic predicate 2 sus sas 55 empty 285500 EE 82 empty Jieap Al i vimse Robots EU REED qa 84 empty gueue l nnne 88 GE 64 95 eraseall T iced d ra be Ra ev ERO REP 59 EKG 9 kde redu ERREUR EDU DEED edi 96 Chapter 23 Compatibility with Other Prolog systems 193 F LIO D 27 file exist8 Lon ase sehen tech bee ee 94 fle Gebei ee eden delen REPE 94 file property 2 i ics etate pere GE 95 Dle search paih icrecriticsruresp iradas 22 hmdall 4 fab aot bak ace erc P seb seppokdetked 62 fl tten csse
20. GCC 2 7 YAP EXTRAS m486 DBP FREE 1 Pentium YAP EXTRAS m486 malign loops 2 malign jumps 2 V 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 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
21. If the goal succeeds unify Result with success If the timer expires before the goal terminates unify Result with timeout Chapter 7 Library Predicates 99 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 0ldTree Label NewTree constructs a new tree the same shape as the old which moreover has the same elements except that the Index th one is Label tree size Tree
22. If you use 3 1 you don t have to worry about such details Alternatively you may use the automatic expansion facility check see Section 12 18 Syntactic Sugar page 131 12 8 Feedback and Bindings What was covered so far was how the user populates the constraint store The other direction of the information flow consists of the success and failure of the above predicates and the binding of variables to numerical values and the aliasing of variables Example clp r A B C 10 C 5 5 B A C 10 0 The linear constraints imply A B and the solver consequently exports this binding to the Prolog world which is manifest in the fact that the test A B will succeed More about answer presentation in see Section 12 13 Projection and Redundancy Elimination page 125 12 9 Linearity and Nonlinear Residues The clp Q R system is restricted to deal with linear constraints because the decision algorithms for general nonlinear constraints are prohibitively expensive to run If you need 120 YAP Prolog User s Manual this functionality badly you should look into symbolic algebra packages Although the cIp Q R system cannot solve nonlinear constraints it will collect them faithfully in the hope that through the addition of further linear constraints they might get simple enough to solve eventually If an answer contains constraints you have to be aware of the fact that success is qualified modulo the existence of a solution to the system
23. Interface function 177 YAP_MkFunctor C Interface function 178 215 YAP_MkIntTerm C Interface function 177 YAP MkNewApplTerm C Interface function prr 178 YAP MkNewPairTerm C Interface function E 178 YAP MkPairTerm C Interface function 178 YAP NameOfFunctor C Interface function ETT 178 YAP OpenStream C Interface function 179 YAP PRESERVE DATA C Interface function semen dale ban red ab dd ge ve eA 180 YAP PRESERVED DATA C Interface function Lig xi qud Hagan te ge Ged ab bekke Fa 180 YAP StreamToFileNo C Interface function EE 179 YAP StringToBuffer C Interface function se der 179 YAP TailO0fTerm C Interface function 178 YAP Unify C Interface function 178 YAP UserBackCPredicate C Interface function izle ed eoe ers S 180 YAP UserCPredicate C Interface function EE NE EEA 180 YAPBINDIR TE 9 Vaptompilelause 186 Vaptontinueoal 0 siscsrerrscr erre bressa 186 YapEndConsult 0 o e vere pe 187 YapErfor i1 o pee gerer bebe 186 YapExit 1 iliioierkeetbueve pere p beer 186 YapEastlInit i1 vem rrr ee be E 186 YapGetValue i eee seere berbere 186 Yapinit 9 rote ERE seeren HORROR 186 YapinitConsult 2 eMe IIT bees 187 YAPLIBDIR 2123443 pEa X Rp Kee HB e 9 YapP tValue 2 o e gege 186 YapRead 4 iod sive tales P TV bep 186 187 YapReSet 0 WEE 187 YapRestartGoal O 20 60 prev ep pes 186 K Ch EE 186 YAPSHAREDIR Co ey PRU RE RA
24. Name does not qualify Currently this only happens if lt Pragma gt is unbound CHR Compiler ERROR found head lt F A gt in Name expected one of F A list Rule Name has a head of given F A which is not among the defined con straints CHR Compiler ERROR head identifiers in Name are not unique variables The identifiers to refer to individual constraints heads via in rule Name do not meet the indicated requirements 148 YAP Prolog User s Manual CHR Compiler ERROR no handler defined CHR specific language elements declarations or rules for example are used before a handler was defined This error is usually reported a couple of times i e as often as there are CHR forms in the file expecting the missing definition CHR Compiler ERROR compilation failed Not your fault Send us a bug report 13 4 Debugging CHR Programs Use option debug compile on preceding any rules in the file containing the handler to enable CHR debugging The CHR debugging mechanism works by instrumenting the code generated by the CHR compiler Basically the CHR debugger works like the Prolog debugger The main differences are there are extra ports specific to CHR and the CHR debugger provides no means for the user to change the flow of control i e there are currently no retry and fail options available 13 4 1 Control Flow Model The entities reflected by the CHR debugger are constraints and rules Constraints are
25. O builtins can be used to write on or read from sockets The following calls are available 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 operating sys tem but at least the following types are supported SOCK STREAM and SOCK_ DGRAM Chapter 6 Built In Predicates 53 socket DOMAIN SOCKET Call socket 4 with TYPE bound to SOCK STREAM and PROTOCOL bound to O socket close 4 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 gt AF UNIX FILENAME gt AF FILE FILENAME use file name FILENAME for UNIX or local sockets AF INET HOST PORT If HOST is bound to an atom bind to host HOST otherwise if unbound bind to local host HOST remains unbound If port PORT is bound
26. OFfd utr0n 2 2 o hho einen dis wie dee eeu t tr DES 8T Ord nton EE 8T Ord unlon 4 ote EPOD kasta 8T e ET EE 87 P Baba Ac ege deg de tc 20 peek bytel esos ere ate erar urges 49 peek Battes ere dE rb RE red 51 peek char 1 sansene susen verse Midst aes AL 49 peek char 2 2 2 oW dde vd ve 51 peek code 1 vu sek h spre b e ERRARE Eng 49 peek c de 2 i e as ee A hadd tita uii ripi 51 permutation 2 oce diga b Fn gut n 85 phrase 2 anire ii nordean a etuer Peg es nen 63 phrase 3 ena na R bred etset 63 UT AMETE RR 96 popen 3 eae c do pier Mee REIR 96 portray clause 1l ev api Ra RR 56 portray clause 2 i eia a ERE 56 predicate Dropertg 5T primitive 1 eios hr DESEE 32 print 1 hed oRBReiker4 bu Li s EVE REPRE 46 LEE 50 profile data 3 1 ida bre EAT 68 profiled dn RER 68 profiling yap flag 2 option 16 program statistics 2 option 73 project attrilbutes lesse til prolog fil n me 2 sspe e ren 22 prolog Flag 3 ine eg E Eeer eet ees de T9 prolog initialization 1 80 prolog load context 2 sess 80 prompt 2 2 322 caii HRAICROUESEEPEIGU aaa T9 Predicate Index public 1 directive see een 22 p t 4 Eed e eee p Saeed eien 4 48 pur 50 put sso c 4 iesu Peg rei Pe 83 put atts 2 user ene RCM ED eS 110 put byte 1 sceed t Ueda dee ee setae pde 48 p t EE 50 put chary ioeo eed tuur aee E bp P PEE T
27. ORG 53 socket buid 2 sis saseseanigaiseiad daa ee mE 53 socket buffering 4 asersntrasennenr eg a 54 socket close l i ess rask dee 53 socket connect 3 seere see tere ERR phase et 53 socket lisben 2 ise tib runie iai E etes 53 Socket select D ii seeds donates REDE sed 54 SOULCE O sensere Oe hte we UR E RE 19 source mode 2 isset err b ha end 19 splay access B i crib Leere n RR ARES 92 splay delete A cessio bees 92 Splay 1nib 9 sx ey skare REF dae 92 splay i1nsert A cisco tre eERTERPR MERE ERU 92 8play JOIn 9 aus dvs Li eet ed bes aba deel a 92 Splaycsplit D e ia eiua anata pr drake nr perde 92 SPY WIe A EE 170 SrandOnu TEE 40 start low level race 165 GEN TO static array properties 3 70 static array to term 3 ss ordenerne 70 SbalisticS 2 skaper press ve RE Pbi dade ed det 72 stream property 2 be 42 siream select 3 err dE eren E E ne 42 sbyle check l nger eere eege ERG 21 GE 34 sub edges 3 cese ns debs Ht bh RARE 101 sublist 2 es odes pen du ETE R EF ETE LEE 86 subsumes 2 in gene Res he mk SE 97 subsumes chk 2 ois seeds DE re eve IRA 97 Sullix 2 viiite elk bikie nite es Meee ness 86 Sum ed eost ened coos E sed 86 EE 81 EE 86 Smets Ee eeh SERA 81 Sumnodes 4 Loch reos te hebetes etes 81 Sygbeni Q EE 97 EE 97 system predicate 2 sunerourrurnrrrrrn 57 T A ENE 51 term h sh 2 i didi ies cence neers vingene 97 term hash 4 esee tn E r
28. Prolog User s Manual 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 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 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
29. 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 from 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 imple mented 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 These builtins are available once included with the use module library ugraphs command 100 YAP Prolog User s Manual vertices edges to ugraph Vertices Edges Graph Given a graph with a set of vertices Vertices and a set of edges Edges Graph must unify with the corresponding s representation Note that the vertices without edges will appear in Vertices but not in Edges Moreover it is sufficient for a vertice to appear in Edges vertices edges to ugraph l 1 3 2 4 4 5 1 5 L L 1 3 5 2 41 3 1 4 5 5 1 In this case all edges ar
30. X YIL B lt H X B Y H B There are no tilings with less than nine squares except the trivial one where the rectangle equals the only square There are eight solutions for nine squares Six further solutions are rotations of the first two clp q use module library clpqr examples squares Chapter 12 CLP Q R Manual 131 clp q filled rectangle A Squares A 1 f Squares 1 A 33 32 Squares 15 32 9 16 1 4 7 32 1 8 7 16 1 32 5 16 9 32 A 69 61 Squares 33 61 36 61 28 61 5 61 2 61 9 61 25 61 7 61 16 61 Depending on your hardware the above query may take a few minutes Supplying the knowledge about the minimal number of squares beforehand cuts the computation time by a factor of roughly four clp q length Squares 9 filled rectangle A Squares A 33 32 Squares 15 32 9 16 1 4 7 32 1 8 7 16 1 32 5 16 9 32 A 69 61 Squares 33 61 36 61 28 61 5 61 2 61 9 61 25 61 7 61 16 61 12 18 Syntactic Sugar There is a package that transforms programs and queries from a eval quote variant of clp Q R into corresponding programs and queries in a quote eval variant Before you use it you need to know that in an eval quote language all symbols are interpreted unless explicitly quoted This means that interpreted terms cannot be manipulated syntactically directly Meta programming in a CLP context by definition manipulates interpreted terms therefore you need quote 1 just as in LI
31. YAP s stacks and execution registers You can use a saved space from a standard system by calling save_program 1 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 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 You can use the term destructor functions to check how arguments were instantiated 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 Fa include lt stdio h gt include Yap YapInterface h int main int argc char argv if YAP FastInit saved state YAP_BOOT_FROM_SAVED_ERROR exit 1 if YAP RunGoal YAP MkAtomTerm LookupAtom do I printf Success n while YAP_RestartGoal printf Success n printf NO n J 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 186 YAP Prolog User s Manual cc o exem I Yap4 3 0 test c lyap lreadline 1m You may need to adjust the libraries and library paths depending
32. 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 Chapter 21 C Language interface to YAP 183 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 e All Names of YAP objects now start with YAP This is designed to avoid clashes 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 interfac
33. 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 N Set a column boundary at N characters past the current position where N defaults to 8 7Nt Set padding for a column where N is the fill code default is SPO 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 Hello 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 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 cur
34. 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 operations and therefore he should try to avoid them whenever possible 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 Chapter 6 Built In Predicates 55 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 system
35. 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 USECS where SECS is an integer gives the number of seconds to wait for a timeout and USECS adds the number of micro seconds This built in is only defined if the system call select is available in the system 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 strea
36. 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 eg counting or collecting data obtained by backtracking As a rule to keep this information the internal data base should be used instead of asserting and retracting clauses as most novice programmers do In YAP as in some other Prolog systems the internal data base i d b for short is faster needs less space and provides a better insulation of program and data than using asserted retracted clauses The i d b is implemented as a set of terms accessed by keys that unlikely what happens in non Prolog data bases are not part of the term Under each key a list of terms is kept References are provided so that terms can be identified each term in the i d b has a unique reference references are also available for clauses of dynamic predicates 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 RO T R Makes term T the record
37. expressions 55 st mar ele rs He Slem ar 90 Splay trees sis vienes IRR UR Aron se ale Weed 91 SUING dei ese ead Er 15 Strine D O c salen rete bee eee oy 92 Cygnus qM DCN m 3 13 T t bling vo Exe Opere ques E ede res 163 E EE 98 LOREM sess 25 cep doen epe P erdt dee deba uds 14 U unweighted graphs ssssrerrrrsrressess 99 updatable tree 42 eed ninin nede E ead res 99 update semantics i2 lp Rr 197 updating terms segere rosea RP days 66 utilities On terms e bel b ERE 97 V variables 2 5cvosedhi aedeuuiessseesncg4 memes 17 218 YAP Prolog User s Manual
38. false The same as fail ISO Read as cut Cuts any choices taken in the current procedure 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 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 1 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 YAP Prolog User s Manual P ISO 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 N P P fail KEE 3 if P did not include cuts not P Goal P is not provable The same as P 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 gt Q ISO Read as if then else or commit This operator is similar to the conditional opera
39. ground 12 12 Numerical Precision and Rationals The fact that you can switch between clp R and clp Q should solve most of your numerical problems regarding precision Within clp Q floating point constants will be coerced into rational numbers automatically Transcendental functions will be approximated with rationals The precision of the approximation is limited by the floating point precision These two provisions allow you to switch between clp R and clp Q without having to change your programs What is to be kept in mind however is the fact that it may take quite big rationals to accommodate the required precision High levels of precision are for example required if your linear program is ill conditioned i e in a full rank system the determinant of the coefficient matrix is close to zero Another situation that may call for elevated levels of precision is when a linear optimization problem requires exceedingly many pivot steps before the optimum is reached If your application approximates irrational numbers you may be out of space particularly soon The following program implements N steps of Newton s approximation for the square root function at point 2 from file library Cclpqr examples root root N R root N 1 R root 0 S R I S R root N S R N1 is N 1 S1 S 2 1 8 gt root N1 S1 R It is known that this approximation converges quadratically which means that the num ber of co
40. 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 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 g
41. in use in bytes global Global stack in use in bytes random random floating point number between 0 and 1 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 40 YAP Prolog User s Manual 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 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 as a new seed for YAP s random number generator The argument should be an integer but floats are acceptable Notes e n 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 availabl
42. information 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 168 YAP Prolog User s Manual Chapter 19 Debugging 169 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 specifi
43. 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 182 YAP Prolog User s Manual static int continue n100 d int n Term t Term sol ARG1 YAP PRESERVED DATA n100 data n100 data type n YAP IntOfTerm n100 data gt next solution ifi n 100 4 t YAP MkIntTerm n YAP Unify amp sol amp t YAP cut succeed else YAP Unify amp sol amp n100 data gt next solution
44. might The predicate ordering Spec gives you some control over the variable ordering Suppose that instead of B you want Mp to be the defined variable clp r mg P 12 0 01 B Mp B 1 1268250301319698 P 12 682503013196973 Mp This is achieved with clp r mg P 12 0 01 B Mp ordering Mp Mp 0 0788487886783417 B 0 08884878867834171 P One could go one step further and require P to appear before to the left of B in a addition clp r mg P 12 0 01 B Mp ordering Mp P Mp 0 08884878867834171 P 0 0788487886783417 B Spec in ordering Spec is either a list of variables with the intended ordering or of the form A lt B The latter form means that A goes to the left of B In fact ordering A B C D is shorthand for ordering A lt B ordering A lt C ordering A lt D ordering B lt C ordering B lt D ordering C lt D The ordering specification only affects the final presentation of the constraints For all other operations of clp Q R the ordering is immaterial Note that ordering 1 acts like Chapter 12 CLP Q R Manual 127 a constraint you can put it anywhere in the computation and you can submit multiple specifications clp r ordering B lt Mp mg P 12 0 01 B Mp B 12 682503013196973 Mp 1 1268250301319698 P yes clp r ordering B lt Mp mg P 12 0 01 B Mp ordering P lt Mp P 0 8874492252651537 B 11 255077473484631 Mp 12 15 Turning Answers into Terms
45. mode on or as declaring all newly defined static pro cedures as public no source The opposite to source The same as source model offi 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 4D N Inserts D in the
46. 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 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 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 List 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 4 List 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 ldQueue 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 Chapter 7 Library Predicates 89 7 9 Random Num
47. of residual nonlinear constraints clp r fsin X cos X nonlin sin X cos X 0 0 There are indeed infinitely many solutions to this constraint X 0 785398 n Pi but cIp Q R has no direct means to find and represent them The systems goes through some lengths to recognize linear expressions as such The method is based on a normal form for multivariate polynomials In addition some simple isolation axioms that can be used in equality constraints have been added The current major limitation of the method is that full polynomial division has not been implemented This is an example where the isolation axioms are sufficient to determine the value of X clp r sin cos X 1 2 X 1 0197267436954502 If we change the equation into an inequation clp Q R gives up clp r sin cos X lt 1 2 nonlin sin cos X 0 5 0 0 The following is easy again clp r sin X 2 2 sin 4 X Y Y 1 0 And so is this clp r X Y Y X X Y Y X 99 1Y 49 5 0 5 X An ancient symbol manipulation benchmark consists in rising the expression X Y Z 1 to the 15th power clp q fexp X Y Z 1 15 0 nonlin Z 15 Z 14 154 Z2 13 105 Z 12 455 Z2 11 136542 10 3003 polynomial continues for a few pages Computing its roots is another story 12 10 How Nonlinear Residues are made to disappear Binding variables that appear in nonlinear residues will reduce the complexity of the nonlinear expressions
48. preceeding record with reference RO and unifies R with its reference recordz at RO T R Makes term T the record following record with reference RO and unifies R with its reference 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 wise make term T the first record under key K and unify R with its reference Chapter 6 Built In Predicates 59 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 referen
49. pte tenes e tbt os edP 84 float T ceci essa EEE EG 32 flush output GENEE EEN 42 flush o tput 1 eg EEN SES 42 format 2 Ae eerie ee kierr rrit ti dd 46 format 5 ves med preterea PR 48 format to charg 9 e gn e EE be RES 92 format to Chars A cioe te TH Ee E 92 fragiles enar runs TRA FADA cone go ERICH ERE 98 freeze 2 cusa s das esas ky DESEE IP PEER 107 rozen 2 das eri ten e dr k Hx RE SERE aS 107 G garbage collect 0 0 cece eee eee eee 30 garbage collect atome eee 30 EE 30 Bell nsS00 EE 82 EE 50 TEE ER et ASSOC D rera e 83 EE 110 get byle l fe eire hE POR Ae EE 49 geb Dyle 2i ires aed apro REOR Heese DE 50 get h r T s inge ate ODE de deque 49 g t chaz 2 manerer nar c RM IT DUCERE 51 get code Luna eels REP Rite aes 49 g t code 2 sann per e tbe PRI Rete P 51 get from heap A servserrsrerde eel ed 84 get l bel 8 2 sie sele et deed 99 get mutable 2 e edo nere EET 67 EE 59 D PM NEP 50 get wd ls aiat osi eet isi LEE Rex tn 64 getrand EE 89 goal_expansion 3 ENEE EIER SEENEN EEN 63 ground l aa et SE ER EI Ed 34 SOW DERP 0 ape tet dn aa dese Es 31 STOW EE St H CR 30 head teuer eto ho VU RR coed 88 heap sme 2 edit dE Ee STE ati dus 84 heap to et EA ag A BEE Ee es 84 EG 20 bide Gredicate 0 cee eee 20 Host id AL e sederit ve cael RIVER 95 host n me 1 ieiseckarieeent tree Rr Pa 95 I NEE FEE VEERE ee eer JD 29 et 29 initialization O e ENNEN ENEE Rem 80 initializati
50. reconsult 1 ensure loaded 1 or use module 2 The non public predicates of a module file are not visible 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 ptions 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 al
51. removing the older constraint and redoing all the propagation with the cur rently active constraint Note that the compiler itself detects the symmetry of the two head constraints in the simplification rule antisymmetry thus it is automatically declared passive and the compiler outputs CHR eliminated code for head 2 in antisymmetry antisymmetry X leq Y Y leq X Id lt gt X Y pragma passive Id idempotence X leq Y Id N X leq Y lt gt true pragma passive Id transitivity X leq Y Id Y leq Z gt X leq Z pragma passive Id Declaring the first head of rule transitivity passive changes the behavior of the handler It will propagate less depending on the order in which the constraints arrive X leq Y Y leq Z X leq Y Y leq Z X leq Z Y leq Z X leq Y Y leq Z X leq Y Y leq Z X leq Y Z leq X Y X Z X The last query shows that the handler is still complete in the sense that all circular chains of leq relations are collapsed into equalities 13 3 6 Options Options parametrise the rule compilation process Thus they should precede the rule definitions Example option check_guard_bindings off The format below lists the names of the recognized options together with the acceptable values The first entry in the lists is the default value option debug compile off on Instruments the generated code such that the execution of the rules may be traced see Section 13 4 CHR Debugging
52. 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 Used 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 fo
53. 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 176 YAP Prolog User s Manual 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 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_ARG2 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 wher
54. that some of these restrictions will be removed in future releases 162 YAP Prolog User s Manual Chapter 16 Tabling 163 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 164 YAP Prolog User s Manual Chapter 17 Tracing at Low Level 165 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 builtins 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 166 YAP Prolog User s Manual Chapter 18 Profiling the Abstract Machine 167 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
55. the previous query void YapWrite 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 void YaplnitConsult 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 Note that it is up to the user to open the file filename The YapInitConsult function only uses the file name for internal bookkeeping void YapEndConsult void Finish consult mode Some observations 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 Currently the YAP library will pollute the name space for your program 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 You can generate your own saved
56. the constraints matching the heads The final is the prompt indicating that you should type in one of the debug options see Section 13 4 5 CHR Debugging Options page 151 13 4 5 CHR Debugging Options This section describes the options available when the system prompts you after printing out a debugging message Most of them you know from the standard Prolog debugger All 152 YAP Prolog User s Manual the options are one letter mnemonics some of which can be optionally followed by a decimal integer They are read from the standard input stream up to the end of the line Return Ka gt Blanks will be ignored The only option which you really have to remember is h This provides help in the form of the following list of available options CHR d c 1 S g amp n lt a C 1 S S1 8 ebugging options r creep e creep leap Skip S lt i gt skip ancestor i ancestors constraints amp lt i gt constraints details nodebug debugging spy this nospy this show rule reset printdepth lt lt n gt set printdepth abort b break help h help creep causes the debugger to single step to the very next port and print a mes sage Then if the port is leashed the user is prompted for further interaction Otherwise it continues creeping If leashing is off creep is the same as leap see below except that a complete trace is printed on the standard error stream leap causes the debugger to resume r
57. the disjunction LS 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 when consulting a file and before asserting or executing it It rewrites a term T to a term X according to the following rules first try 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 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 1 Both this predicate and the previous are used as a convenient way to start execution of grammar rules 64 YAP Prolog User s Manual C S1 T S2 Th
58. the file leq pl The code works regardless of options switched on or off use module library chr handler leq constraints leq 2 op 500 xfx leq reflexivity X leq Y lt gt X Y true antisymmetry X leq Y Y leq X lt gt X Y idempotence X leq Y X leq Y lt gt true transitivity X leq Y Y leq Z gt X leq Z The CHR specify how leq simplifies and propagates as a constraint They implement reflexivity idempotence antisymmetry and transitivity in a straightforward way CHR reflexivity states that X leq Y simplifies to true provided it is the case that X Y This test forms the optional guard of a rule a precondition on the applicability of the rule Hence whenever we see a constraint of the form A leq A we can simplify it to true The rule antisymmetry means that if we find X leq Y as well as Y leq X in the constraint store we can replace it by the logically equivalent X Y Note the different use of X Y in the two rules In the reflexivity rule the equality is a precondition test on the rule while in the antisymmetry rule it is enforced when the rule fires The reflexivity rule could also have been written as reflexivity X leq X lt gt true The rules reflexivity and antisymmetry are simplification CHR In such rules the constraints found are removed when the rule applies and fires The rule idempotence is a simpagation CHR only the constraints right of W will be removed The rule says t
59. timpani does ER QNS 89 212 M make directory 2 sees 95 make queue 1 ob eee ae tee eee meena 88 H p ASSOC 3 dig ced cee two ne aden eee dees 83 map TLS Bis d e eee ose rroka SP de d 99 Mapargs S itech ieee eruere te eedem aes 81 MAPlASt S EE 81 napnodes 3 EE 81 max arity yap flag 2 option 75 max integer yap flag 2 option 76 in mber 2 AA ed Pee aa Ae ee he aed 85 nemberchk 2 1 AN le Ee RET Pas 85 merge 3 2x 2m cn de LIT Ra e ediee s 86 meta predicate 1 directive 25 min integer yap flag 2 option 76 min of heap 3 42244 enu graded pts 84 min Of heap b i icum pRR RR e RN ERU ne 84 mitemp 2 eer e Ee p 95 module prolog load context 2 option 80 modile 1 haren irni ap desta ces esta exi idea er 24 module 2 directivei 24 module 3 directive 24 multifile 1 directive 21 N n of integer keys in bb yap flag 2 option PU desde EE E Pid ea E ER PE 76 n of integer keys in db yap flag 2 option EE EE ENGE MERC 76 name 2 pages Aeg naa dessa Sa ie uka 32 neighbors 3 ei ik s b e dos dees ud 101 neighbours 3 sicsrse dua e EE 101 new l iilizilaaegeceewun E 89 TE E rau RR URP de Yu Rd PES E was 50 nl 1 ae be EEE vene S NO SOUTCE O an svansk sbeiew9 je ripe Gad eee ie 20 no style check 1 vices et p beac 21 nodebug O 2 d e err b e RP ERE IDA 169 nofil errors 0 2 dlus sis d p
60. 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 gt AF UNIX FILENAME AE 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 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 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 AE NET 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 54 YAP Prolog User s Manual Socket buffering SOCKET MODE OLD NEW Set buffering for SOCKET in read or write MO
61. to top level All break levels see break 0 below are terminated It is mainly used during debugging or after a serious execution error to return to the top level 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 ha1t 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 FE 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 g
62. versions except that this permission notice may be stated in a translation approved by the OFAI e 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 is distributed separately from yap tex Copyright 1998 2001 Paulo Moura e 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 e The yap2swi library implements some of the functionality of SWI s PL interface Please do refer to the SWI Prolog home page http wuw 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 1 2 3 SO Dor hee Installing YAP To compile YAP it should be sufficient to 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
63. 0m e har EE 59 erased 1 Rashes hades ae ddd il EVEREST 59 exec 3i uud pelos bbc RN OUR ee dene ea 96 e xasts i sedes tout Beatie ire oa Ud ates 52 expand expr8 2 4 0 6 eekRR o xa tr Ep 20 expand term 2 es 2 429 p REP EI 63 F Fell Oline den 27 PAU SS Oo Liter aa dere See de 2 fast yap flag 2 option 74 file prolog load context 2 option 80 file exists 1 RR reed dn ebay rs 94 file exists 2 oido eee a eee te E 94 file property 2 2 3 0 irete REPARTO Ed 95 file search parb eee eee 22 fileerrors yap flag 2 option 75 file rrors 0 1 tekkes ener RUE 52 find sconstraynt 2 ui cec onem king 145 find c nstraint Stsualssiarussrenekunklee 145 findall 8 ee eq au buch DEED ammet d 61 findabb 4 EE EE 62 Predicate Index findall constraints 2 sess findall constraints 3 sss flatten 2 o suco aun aar use eno yr meal Ee e E flush output ses steels d SS flush o tput EE EEN ee EE format to chars 3 2 2 22 ER oh format to chars 4 dicla d waa eei fragile etei seis adeb qr aee aed d do freeze 2 eege iliud dagdilescpergg rede frozen 2 iier oe herds ku da Lee sak Y ea f nctor 3 23 d pube 9 a eh seder G garbage collect 0 2r ge res garbage_collect_atoms 0 garbage collection statistics 2 option gc yap_flag 2 option EC Qi ci pene ebore HR Ru SEU e S
64. 4 discontiguous 1 directive 21 display l ccce koe uir ER REV eR AEN H 45 50 display E sso g et Ae Se AR des 50 E empty assoc Ui neon REALI ERROR RECO 82 empty h ap 1 ENEE de 84 empty oueue l eee eee eee 88 ENEE a ee ee 64 95 EE 96 expand term 2 sess ps 63 F Pusen 27 false 0 couch Ae babe Be 27 file exists EE 94 UE 94 file property 2 icm pre rh sande deem 95 fhile search path 2 seas eee bh EV he 22 flleerrors Oise osse ika e ben bete idend 52 PI AB es ie ede ostii e bd 61 findall 4 is bee uds tera o ce CR XO 62 flatten 2 se se sebo dng arm UO ants nee edhe duets 84 float 1 35 Seet oo kdb bibs keine eng ae aed 32 Husk output eege bte et eter apes 42 flush output 1 ripeciirpies iesp iodin reri 42 format to chars 3 oec credet eee eee ge 92 format to chars A dE ER 92 fragile 5224 x enese ent reker ege sek 98 freeze 2 isssses opido Yee pRRTGUAdA e b ERE 107 rozen 2 spur enker Roni EE ENG 107 f nctor 3 eise tero kanne E ER SE baked 34 G garbage collect 0 2 sats sner banner erne tsu 30 garbage collect atomsa esses 30 EE EE 30 gen a8800 8 sioe bum E ERR EHE 82 get lotus reg Rituals syst E Een n Habl ined 49 BOL E Up di teet i secs dd 50 get BS ad bar bed Peder hedre gere 82 Bet as806 B co rasen PIE ER bere bread 83 Feb als 2 etd icit eg Pete DI Pedes 110 get from heap A cuui e ERE AE RE 84 get label 3 cies de gr ste EU PE E T AME D 99 get mutable 2 s
65. 44 EE 97 SyBten 1 isses coe X MOSROPepM RED Rede 64 EE 97 systen Dredicate i iora s inntinu 57 ABZ EE EE a trao Maa RAS 50 VIP ERE eege E e 51 COU pina bh ba pe E xau a Edo rs 43 ke EE EE 43 term expansion 2 sees 63 term HASH eine tae fee EPUM 97 term hash 4 c iue bg etae RET ae 97 term egal eege geed de 97 throw l lons zebexi Re ad ato een e ERE 30 time EE te eege A dE reg A 98 EE gece teg d e e adeps 96 to chars modes yap f1ag 2 option TT told O hie lee SN oe a b a e dit 43 top SOEbt 2 Ls svanen wie bre ses ERR auos 102 toplevel hook yap flag 2 option E trail statistics 2 option 73 transitive clLosure sss 102 transpose 3 i os rg hes Sa eaten eae DERI 101 trea size 2 1 3 d Igi aa ep IIIS 99 tree to Tist 2 EE 99 trues Leu M EA SER 2T ttyget l eL AEN Relais PERPE PUEDE 51 ttygetO 1o ited peris he dentia 51 EECHER eege 51 ttiyDut d cooni hber DUE neq LU Ete 51 ttyskip l M PEPERIT 51 ttyt b io 2 cis Eee LR ER EIE eS 51 typein module yap flag 2 option d YAP Prolog User s Manual U unconstrained l sussssarnanehenasstensateed 145 WHHIdE EE 20 unify_with_occurs_check 2 35 EE DEE 64 unknown yap flag 2 option 78 nknown 2 i 2eekcbeek ker ke IRIS al unknown predicate handler 3 32 update array 3 rdr ve tna sade besa 71 update mutable 2 eee eee eee 67 update_seman
66. 49 peek Godert eee enced ba eneste 51 perinut tion 2 senn des eee reseed ristet er 85 phrase 2 i ane e ii des ite codes 63 inc TEES 63 et 96 YAP Prolog User s Manual POPE skisse og Weep eek diet 96 portray clause l an sosdsdisenkenskansndeej er 56 poriray clause 2 s soe RR RR URDU 56 predicate_property 2 0c cee eese 57 E pnm 50 profile data 3 ccce EE dE RR 68 profiled_reset O 00 00 0c eee eee eee eee 68 project attributes 2 2 00 111 prolog file name i ene 22 prolog Hag 9 iii deeds eda rev mter PE 79 prolog initialization 1 0 002 80 Grolog Joad contest crrrrcesrccrreri cres 80 public 1 directive 206 aser treerne 22 pub2 cess delcerpeR P pUD UN ERE eI OPE seed 50 put 8880674 ped rekke e E Re Ue ERES 83 E EEN 110 pul byte l assi e RED URP 48 put byte 22 sag ed med 50 p t char I os Succ geet ceases ege vg pce eg 49 jid PEE 50 et TEE 49 er TEE 50 Pub label coe Lee eerte ape da edis 99 pubeny 2i sisse eens aneh I sade OUR IER du 64 Q queue to list 2 coser ee ete wees 88 R rapdomnyjds EE 89 Fabdom u osiede oe sme siad iade tp bath edet ma 89 E EE 89 randsel 3 Deos pte oen Ee EFE 89 EE 8T E EE 88 ransbart T c ioi ker courant ined PI OU v rres 88 EE es 88 reachable 3 3 2 reper ve ra Rep deg E 102 WORD EET rU bee Me 50 read from chars 2 dE dy seer E ER ee Ra 93 read term 2us iot clad neret E Ti RP ROPA 44 read term 23aii ci esr sve rep
67. 5 WElbeq repper iertare orire PU PISO AE ENS 45 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 compatible A EE 55 abolish 2 2 chen busco tutae t gud ta ep ERE 55 assert Io bet be obe deep REPLIES 55 o D PD 57 asserta Lee eee ke spe alee ay TRES 55 EE 58 ASSEUZ siot seda net VEL M RP OE RP 55 aSSEUZ 2 assu eaa e eR ERR RA Eque dd 58 C clalise 2 s bostes n RE Res S Rs 56 clause 3 EE 56 I SE 39 L listing 0 succede ta apibaiagacs EE E dE de 56 ebe passe aat ne rv OPERA DP sass 56 N nih clause 8 iis t be E RIEN EE Rr ed AE 56 R WELLACU dere SNE SEERE Eeer Ae 58 23 1 4 Yap predicates not available in C Prolog These are YAP built ins not available in C Prolog 192 absolute file name 41 add edges 8 ciere er eher 101 add to array element 4 u uninrrnrrrrrnne 71 add to beap ft see oret SE ee NEE 84 add vertces 3 seni bens me pre ERE ERES 100 Slam Agang 65 EE 62 alwans Drompt user 000s eee esee 52 ee KEE 84 STE e eden 34 BELAY OE 70 array element 8 enere E RENE re heben ss 71 assert static 1 cese eed pret I Pep RES 55 asserta static EE 55 assert state Lu ipee doko asec OPES 56 assoc to list 2 desk ia deans dene Rr te MEER 82 at end of stream 42 at end of stream 1 slssseeees esee 42 atom chars 2 4 ctus DERE tet IEEE ad 33 atom code
68. 7 7171 op 1050 xfy gt op 1000 xfy op 999 xfy op 900 fy t not op 900 fx nospy spy op 700 xfx gt lt lt gt lt gt gt lt is op 500 yfx NV NP 29 208 0p 500 fx 7 op 400 yfx 3 5 95 9J4 fr 4247 2 9 op 300 xfx mod op 200 xfy op 50 xfx same YAP Prolog User s Manual Predicate Index Predicate Index 209 A abolish 1 2 udo do c ts bose ver dm E 55 abolish 2 2i 0 E RE SEA Kea GaSe dee 55 Sboek f ei piere eR EE RR ada Rae dae 30 absolute file name sess 41 add edges 3 o oce cP Rests ow deta ned es 101 add to array element 4 71 add to heap 4 amp i e illl ee preke E SE CE 84 add to path i i piri banh Pb dore dace es 20 add to path 2 sen aida d ce bod 21 add vertices 3 lesen 100 alarms disi ae wasted sere pal Sided Ghd yess Berle evs 65 BBs uu lerem d don add aqu SNE RENE NEDEN Sage 62 always prompt user sss sseeeee 52 append 3 i dax aac dr sg eor x peu dedu us 84 EG EEE ENE 34 argv yap flag 2 option s T3 array 2 coics EEE d yeah drea 70 array element 3 edd bna patema RE Fa assert 1 1i 0 22 decur REISEN 55 aSse rt 2 bod de smedl RR Esc dvs oT assert ststic lT 1x 2 fedens 55 ass rta i slice Ree nepina ends 58 asserta 29 224 ebbe quu ee Ed dcs 58 asserta statric i
69. 8 The debugger message will be shown while creeping or at spy points and it includes four or five fields Chapter 19 Debugging 171 e The first two characters are used to point out special states of the debugger If the first character is a execution is at a spy point If the second 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 debugger command is just a character followed by a return By default only the call and redo entries are leashed but the leash 1 predicate can be used in order to make the debugger stop where needed There are several commands available but the user only needs to remember the help command which is h This command shows all the available options which are c creep this command makes YAP continue execution and stop at the next leashed port return creep the same as c l leap YAP will continue execution until a port of a spied predicate is found k quasi leap similar to leap but faster since the computation history is not kept useful when leap beco
70. 86 Ord sebeq 2 EE 8T ord setproduct 3 SEENEN ese rv RETI 87 ord subiract 3 e edente RR A EE 87 ord Synd 3 sides teniente ntie RR Pda denas 8T ord niomn 2 oz reed eens rere bep At 87 ord union EE 87 ord Union d cesses ne tren PEE EMEN EE UG 8T ordsubset 2 34 aote eet Dis re E te aeg 87 P pek Ebert A et Sege g et gc SE 49 permutation 2 0 066 602 e i teer E 85 phrase 2 na erred ben epa wp cbe rbd 63 plirase 9 vids die dree dere d ende 63 led 96 POP PE 96 portray Cause b EA EE A 56 portray clause 2 i see tere Er RR 56 E E EE 32 printy oco aE a E E SA 46 EE EE 50 project attributes 2 0 000 111 prolog file name l sees 22 prolog Mae 3 iia ce eke radarene ELE 79 prolog Joad contest 000000 80 DrOmp 2 i seris berries enehi tented des 79 103040 ANE 48 put Zeenen reani per dd tp RE anbe P ee 50 PUL ASE0G ele A P bere ere 83 Pub tts 2 sure edie EE ed 110 pub zlabel M rosae ERIS daniels 99 Q queue to lisb 2 o s ex hetsende ee rpn easy 88 Chapter 23 Compatibility with Other Prolog systems 201 R random EE 89 ratidom 9 ccevebe atte nerd a eee t budt en 89 randseq 34 Eed EE EE 89 lee Ate d Ee eg RR REG 89 reachable 3 2 obs Spes t itecto reete E PO 102 Tead linsene usua utu PE 44 EE EE 50 read Bremm here csse pet b UPPER AI oes 93 remove duplicates 2 0 00 0000000 85 rename file 2 ee NEE eneret rsu 95 Tepeat U c secs REE EBBE RES ote pP aged 28 res
71. 8793143805903554 7928682131082164366007016698761961066948371407368962539467994627 1374858249110795976398595034606994740186040425117101588480000000 0000000000000000000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000 2629990810403002651095959155503002285441272170673105334466808931 6863103901346024240326549035084528682487048064823380723787110941 6809235187356318780972302796570251102928552003708556939314795678 1978390674393498540663747334079841518303636625888963910391440709 0887345797303470959207883316838346973393937778363411195624313553 8835644822353659840936818391050630360633734935381528275392050975 7271468992840907541350345459011192466892177866882264242860412188 0652112744642450404625763019639086944558899249788084559753723892 1643188991444945360726899532023542969572584363761073528841147012 2634218045463494055807073778490814692996517359952229262198396182 1838930043528583109973872348193806830382584040536394640895148751 0766256738740729894909630785260101721285704616818889741995949666 6303289703199393801976334974240815397920213059799071915067856758 6716458821062645562512745336709063396510021681900076680696945309 3660590933279867736747926648678738515702777431353845466199680991 73361873421152165477774911660108200059 The decimal expansion itself looks like this clp q e 1000 E print decimal E 1000 2 7182818284 5904523536 0287471352 6624977572 4709369995 9574966967 6277240766 3035354759 4571382178 5251664274
72. C 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 5 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 8 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 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 Outpu
73. COMSPEC if SHELL is undefined in this case with the option c Chapter 7 Library Predicates 97 sleep Time 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 system Start a new default shell and leave Yap in background until the shell completes Yap uses bin sh in Unix systems and COMSPEC in WIN32 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 is from 0 to but not including 33554432 term hash Term Depth Range Hash Unify Hash with a positive integer calculated from the structure o
74. Conference Workshop on Constraint Logic Programming Systems Washington D C 1992 Holzbaur 92 Holzbaur C Metastructures vs Attributed Variables in the Context of Extensible Unification in Bruynooghe M amp Wirsing M eds Programming Language Implementation and Logic Programming Springer LNCS 631 pp 260 268 1992 Holzbaur 94 Holzbaur C A Specialized Incremental Solved Form Algorithm for Sys tems of Linear Inequalities Austrian Research Institute for Artificial Intelligence Vienna TR 94 07 1994 Jaffar amp Michaylov 87 Jaffar J Michaylov S Methodology and Implementation of a CLP System in Lassez J L ed Logic Programming Proceedings of the 4th International Conference Volume 1 MIT Press Cambridge MA 1987 Chapter 13 Constraint Handling Rules 137 13 Constraint Handling Rules Copyright This chapter is Copyright 1996 98 LMU LMU Ludwig Maximilians University Munich Germany Permission is granted to make and distribute verbatim copies of this chapter provided the copyright notice and this permission notice are preserved on all copies Permission is granted to copy and distribute modified versions of this chapter under the conditions 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 chapter into another language under the abo
75. Current EE 79 current utput 1 1 asser er maren 42 current Dredicate s 57 current predicate 2 s sess 5T current prolog flag 2 s s 79 ef a E eds ERE s 42 YAP Prolog User s Manual cyclic term 1J lo iisdem xe Rx pace d 97 D SET e Ate EE EE and 94 db reference 1C eee 32 debug yap flag 2 option 74 debug 0 visse cease isch ede Ere ELE ER ERU ai 169 debugging 0O o erue orae patieris 169 del vertices 3 2 bos ndr De PRRRS 100 delete 3 Regen ai dee Shetek wes 84 89 delete f11e 1 ede Eb See d 94 delete f11e 2 2 10 009 ti eeri br De 94 ED 4 cet ahead cathe ete eee ee ate pedal 107 directory prolog load context 2 option 80 directory files 2 dp REPARARE ba 94 discontiguous 1 directive 21 discontiguous warnings yap flag 2 option EE 74 76 display i gg ger Eet Eed tales bie ean 45 50 diSplay 2 eiiis RET an e peer sd ee de 50 do not compile expressions 0 20 dollar as lower case yap flag 2 option 74 double quotes yap flag 2 option 74 dyniamic 1 oeei uniron dt rota Vr saa EEN HERO cde 54 dynamic predicate 2 op eese RR 55 E empty assoc losi exige vber eres the oa Hs 82 empty heap 1 cere eaten PRO un 84 empty queue 1 i pL e px 9 re ve ES 88 ensure Losaded esee 19 enyiron 2 i6ebsece dekkes twee be ates 64 95 erase 1 05 1ssnsbspg dac eade d eet akan 59 eraseastl 1l 2 25 d
76. DE 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 before socket select 5 returns The variable SOCKETS is a list of form KEY STREAM where KEY is an user defined identifer 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 reconsult ing predicates are
77. E 58 retractall 1 2 2 passa alerede 56 TOVETSE 2 geb fu RARO EN 85 runtime statistics 2 option 73 213 S same length 2 6 Deeper RT EYES 86 save i istrie ed ERR need edhe LEG Ed 22 save J sli idad a e ed HE Canoe Fi 22 save program 1 cep dedia teeny aedes 22 Save program 2 A tee d dE EE 22 TN NE rm 44 Sceinp il i Renee bend 44 Seeun 03il lsLlpeubr ecc De DOM UP MOTTO 44 SelsCt 3 vene pb rae HEFTE S Keren 86 sele ctlist 3 l 5h xode 4 we IP E REES 81 serve queu e 3 ee NEEN SEN ees ede rds 88 set input 1i l5 4m od ee deeper RP die 42 set output eiretie ae RM DRE Rer dE 42 Set prolog flag 2 eet ege Eer Eege 79 set stream position 2 sss 42 set value 2 EE 59 SCtare SM atic hist cee hee He PR Ra 67 E EE 62 setrand l Age rege AE 89 ov OE qiie Ped us sonam vind dis 64 Shell da 452a dre Yer uci suede edad 96 See A Uer PIC dE auta vies bad d 96 show op Counters l esses 167 show ops by group l sanse hehe 167 EELER re 32 single var warnings yap flag 2 option 76 singletons 1 read term 2 option 44 t os Lords 49 TEEN 51 CN ERE 97 e RE EEE eee 53 SOCKCE 4 Cr 52 socket accept eee eee eee eee 53 Socket accept 3 csse ce p pi AREE rd 53 socket DANS EE 53 socket buffering i cscicccricrrisorerirreri 54 socket eleee ft genres Sa Sg l Se EE 53 socket conn ct 3 EE 53 socket listen 2 deni 53 socket select b eee 54 SOFC Diesen fo lea A
78. EE ERE GRE 10 216 YAP Prolog User s Manual Concept Index Concept Index A anonymous variable association EE attribute declaration attributed variables llus AVL 1668 154 uadeere tre RR ater EE EY EY vadis B D r ie SEA Ate ie PI en dud tees C CHR control flow model CHR debugging messages CHR debugging options CHR debugging predicates CHR spy points ee cire mkv ek Rene RR clean p EE COMMENT suceden me eder hae belied seie Counting Calls 4 24 e ERE ese ewes D declaration attribute 000 E end of terim essa a4 EE denen AERE dos environment variables F floating point oumber prr orertiannrenrer iseia installationer daea RE E EE EREN INGES hen da Ios a ee EM eee L list manipulation 22 2 ERREUR ERR logbtalk 2 mcieiza Re eesidRew Reni casados 217 M machine optimizations lisse lees 4 MACOS 2c mene sene POP qux eS 81 mutable variables eese eeeees 67 N Dune EE 14 Operating System Utilities 94 or parallelism 2 524 reo EI bee EUREO 161 ordered Set uode ridi rero ER RR EE RE 86 P parallelismi EE 161 prohiling eios cess Coa ees 67 pseudo random sedis d SS ead Rhe 87 punctuation token carar Bae wee ein mer T QUEUE s sever eam FER Ead cepe dris 88 89 R Red Black rees 89 regular
79. FromYap C Interface function Ede deo bdo tte quud ee add Raps fes de 179 YAP ArgOfTerm C Interface function 178 YAP ArityOfFunctor C Interface function ee EE 178 YAP AtomName C Interface function 177 YAP AtomOfTerm C Interface function 177 YAP BufferToAtomList C Interface function BEE 179 YAP BufferToString C Interface function EE 179 YAP CallProlog C Interface function 180 YAP CloseAllOpenStreams C Interface function ede RU dade usa 179 YAP cutfail C Interface function 180 YAP cutsucceed C Interface function 180 yapcflag 2 vaso ita FER ER PAAR 73 YAP FloatOfTerm C Interface function 177 YAP FreeSpaceFromYap C Interface function BEE 179 YAP FullLookupAtom C Interface function pidgsdoseenb0se due ME Fee YAP FunctorOfTerm C Interface function reor 178 YAP_HeadOfTerm C Interface function 178 YAP IntOfTerm C Interface function 177 YAP IsApplTerm C Interface function 177 YAP IsAtomTerm C Interface function 177 YAP IsDBRefTerm C Interface function 177 YAP IsFloatTerm C Interface function 177 YAP IsIntTerm C Interface function ETT YAP IsNonVarTerm C Interface function 177 YAP IsPairTerm C Interface function 177 YAP IsVarTerm C Interface function 177 YAP LookupAtom C Interface function 177 YAP MkApplTerm C Interface function 178 YAP_MkAtomTerm C Interface function 177 YAP_MkFloatTerm C
80. Ode eet ketone betes db p SE er 50 EU EE EE 64 R rannu fl 5icveoce re REPE RR rever RTI 87 ranstarb Q eg eene er eres 88 ranstarb l 6 cele Rer ninien EHE 88 EE 88 reconsult l 2c efereetble ERNEST 19 recarda 3 EE 58 e EE EE 58 recordaifnot 3 eese arne RR ple RERO PIS 60 E EE 58 recardzifnob 3 ences reete rper ted 60 Yegexp d cssesseetersesenetums vivre up me RE 90 EE 90 remove from path 1 sssesssesssess 21 rehame 2 svin eieepxpexee ee ep ere TIPPS 64 reset op Coumntera 000 167 resize static array 3 sus seeren reverse 71 S Save EEE adea botes atu ac pita 22 Saved tote cR TIE ER ERAS 22 selectlist B vede rise deeg tree e e tae hs 81 set_prolog_flag 2 0 cece cece eee 79 Seb value r aere dated Loe wants dnb eb ake 59 SGLATE OIL s p ser passene edet ise t 67 REN 64 YAP Prolog User s Manual show op counters ess 167 show ops by group 1 eere 167 SOURCE EE eed 19 So rce mode 2 d irte ead AE eue ea a 19 Spl y B6cess D EE 92 splay delete 4 vnc roriri teri Re ge 92 splay Mit 3 cerise teach eee eee eee IP nud 92 splay insert A EE NEE ER re 92 Splay jon 22 2oeza ce ae edge SRM Md 92 splay SPUD goeod ara stated kakene 92 Spy WEbe 2 i re pling Whale ean Vena ede 170 A EE 40 start Joe Jevel race t usuusurrrrrnne 165 Stallc array d c cence eed sanket baser UU 70 71 static array properties 3 sies esses 70 static array to Ierm ore icsrrerpaiirirerii ti TO str
81. P 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 S SEERE EN 27 RE EO TREO 27 lt EEE ten 40 EEE EEE ENER 27 190 EE EE 40 D 40 AMEN 36 EE NE TES 40 gt eee 40 EJ 40 Q OG ENDE REIR LR 36 C dende ones dd dr 36 VE dd der 36 Bom 19 ja prm 19 Um 28 3X 36 A EE 30 STOL ere Rigel epu ds wie FERREA POP 32 abomuc l ciobleseR5beRE eR anced PIU CH PESE 32 B horno n 62 eating daw DEE de ed 30 C CAM sires deers dene ka tees PE ERES 29 CSE EEE HR 41 COMPALE 3 asia decer ay eb ee ded daa 35 consulti eei kerone shee EDU RIS PA Og Bg 19 Current atom Il gedreet peer pre TEN 57 current pr dicate 1 045 sis tere Ri preg seen 57 D db referenee lassiaassindregvneker fate 32 ebe A usteet bent bim LPS 169 debugging Orori ced eee etek dE ee ska 169 display Lis oj nies Aender REM DEUS 45 YAP Prolog User s Manual E erase l ici keRibesttarbRRR nade e RATONES 59 erased LeisssbetbrcetbR e REC PE AP ET det 2 59 Ou RR PD m 52 expand expra8 2 EE 20 expand term samer sr RR YR samer 63 F EE EN 27 fileerrors 0 EE 52 findall 3 det EPI RA NEE E 61 EE 34 G I NE EE 49 Eet0 EE 49 H h lt ii iesasesecese ce
82. SP and some means to put syntactical terms back to their interpreted life 3 1 In a quote eval language meta programming is pragmatically simpler because every thing is implicitly quoted until explicitly evaluated On the other hand now object pro gramming suffers from the dual inconvenience We chose to make our version of clp Q R of the quote eval type because this matches the intended use of the already existing boolean solver of SICStus In order to keep the users of the eval quote variant happy we provide a source transformation package It is activated via use module library clpqr expand Loading the package puts you in a mode where the arithmetic functors like 2 2 and all numbers functors of arity 0 are interpreted semantically clp r 2 2 X X 4 0 The package works by purifying programs and queries in the sense that all references to interpreted terms are made explicit The above query is expanded prior to evaluation into linear 12 0 2 0 X The same mechanism applies when interpreted terms are nested deeper 132 some predicate 10 f A B 2 2 cos A Expands into linear Xc 2 0 cos A linear Xb A B 2 linear Xa 10 0 some predicate Xa f Xb Xc YAP Prolog User s Manual This process also applies when files are consulted or compiled In fact this is the only situation where expansion can be applied with relative safety To see this consider what happens when the toplevel e
83. Set2 Difference Holds when Difference contains all and only the elements of Set1 which are not also in Set2 ord symdiff 5et1 Set2 Difference Holds when Difference is the symmetric difference of Set1 and Set2 ord union 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 2 w 1 1 where w is the word size available for integers e g 32 for Intel machines and 64 for Alpha machines Note that the numbers generated by this random number generator are repeatable This generator was originally written by Allen Van Gelder and is based on Knuth Vol 2 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 88 YAP Prolog User s Manual 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
84. Spy points resetea huisa eR eg 150 13 44 CHR Debugging Messages 151 13 45 CHR Debugging Option 151 13 5 Programming Hints een ttt pete s 154 13 6 Constraint Handler 155 13 7 Backward Compatibility 00 0 0002 e eee 157 14 L gtalk ee Baan a ee ac e RS va 159 15 Parallelism sg 2602026 hb n REPRE ER RECTE 161 I6 Tabl eespesees 9 net y eR RE pandena 163 17 Tracing at Low Level er ww 165 18 Profiling the Abstract Machine 167 19 JDebugsingi esase zs ya kk RR RES 169 19 1 Debugging Predicates llis elei eee eee eee 169 19 2 Interacting with the debugger 170 20 Pole daad e Ee Ee Ae REGE ue 173 VN MESS TP 176 21 2 Umnification 243422 ed eeepc de red p LA Ge M ok 178 21 3 SUVS osea di redet reso eg prole dac e d eee 178 21 4 Memory Allocation 179 21 5 Controlling Yap Streams from 179 21 6 From C back to Prolog Kg NEEN E KE eb Ee ER Rs 180 21 7 Writing predicates mt 180 21 8 Loading Object les 182 21 9 Saving and Restoring 0 cece eee eee ee 183 21 10 Changes to the C Interface in Yap4 183 22 Using YAP as a Library 185 23 Compatibility with Other Prolog systems Mr 189 23 1 Compatibility with the C Prolog interpreter 189 23 1 1 Major Differences between YAP and C Prolog rm 189 23 1 2 Yap predicates fully compatible with C Prolog E EE mM D d Je 189 23 1 3 Yap predicates not strictly c
85. ULCE O ns ccrte uA UDUDR CEDERE 20 nu m Em 30 GE CH EE 169 Md MEMMIUS 85 Ina MEHREREN 85 nth recorded 3 eec eres 59 nb cesses emen 85 T 85 number atom 2 22 lace ive peta eH End 34 number Chars Di A eb dad rie e ew qa 33 number codes 2 tuper EROR EPOR 34 number to chars 2 as servananmne EE es 93 number to chars 3 eie EEN SE 93 n mbervars S ccecoeiohebe cR ee eed ceded den 34 O on eleanup 1 ies ei toe ERREEUE aitort ai 98 on signal 3 ict serirteriv m bia eee Deke 66 Once EE 30 Open Sars rose eique tere aeu 40 Ope EE 41 open chars stream resrerricreiceriss 93 ord ad element 2 86 ord del element 3 00 00000 005 86 ord disjotnt tree A ctetu ent tek 86 Ord 1nsert 3 ss presser ek Geek desk EE RU 87 ord intersect 2 nies e er ue A d re ing 87 ord ken ee caesi Seet Eege E Ee Seed 87 ord list 16 25800 2 earne mei e dd eda 83 Ord Eed soe o pP PLU doin d v de ote 86 ord s teq 2 Loco pote Due ped dea ee ae ees 87 ord setproduct 3 esos tret ERR 87 ord subtraet 3 op ted E Re E tas 87 rd sy erpen ienr e da fy 87 ord zuniou 2 adr lse cate aA enden 87 Ord uniOn 3 AEN ieee Bek EET RS 87 OFM MMOD 4s cies s saa berbere 87 ordsubset 2 ius chee agence pas ELK RR REIS 87 P Path saa ri adi pct fern ei Dodd ide 20 21 peek Byte l sce cbestUenbersem gies seede 49 peek byte 2 iei e NU EL E REM RU 51 pek Char Uris cete rentes d peperere 49 peek EE 51 peek code c scent iin b gerne
86. User s Manual b break calls the built in predicate break 0 thus putting you at a recursive top level When you end the break entering D you will be re prompted at the port at which you broke The CHR debugger is temporarily switched off as you call the break and will be switched on again when you finish the break and go back to the old execution Any changes to the CHR leashing or to spy points during the break will remain in effect help displays the table of options given above 13 5 Programming Hints This section gives you some programming hints for CHR For maximum efficiency of your constraint handler see also the previous subsections on declarations and options Constraint handling rules for a given constraint system can often be derived from its definition in formalisms such as inference rules rewrite rules sequents formulas expressing axioms and theorems CHR can also be found by first considering special cases of each constraint and then looking at interactions of pairs of constraints sharing a variable Cases that do not occur in the application can be ignored It is important to find the right granularity of the constraints Assume one wants to express that n variables are different from each other It is more efficient to have a single constraint all different List of n Vars than n ninequality constraints between each pair of different variables However the extreme case of having a single constraint modeling the whole c
87. 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 452222999 B bade oS S05 SeRPSERERRERSeS 1 l ZInetalhng VAP ee geg orina 3 1 1 Tuning the Functionality of YA 3 1 2 Tuning YAP for a Particular Machine and Compiler 4 1 3 Tuning YAP for GO 4 1 3 1 Compiling Under Visual Ca 6 1 3 2 Compiling Under SGClscerc d 2 Running YAP os ccsstnds E Ee EEN 9 2 1 Running Yap Interactively lssseseeeeeee eese 9 2 2 Running Prolog Elles sete eee ees 10 3 Syntax essersi xu Fas Y xr rese xs 13 3 1 Syntax of Terms 2m EELER dh eee baskere 13 3 2 Prolog Tokens uau snare 9d xau echte dud roe ded Fest ex e ike 14 Ss Abee erer do Quels n cete te eanet ie s 14 3 2 11 Integerg esses ee 14 3
88. a d md 52 NOBC O E kar b e dg 30 nonvar 1 5etesxXE e ELPeLL edad eese 32 NOSPY EE 169 nospyall O oss eec EET a ER eere ds 169 Hob less tom URDU E UE 28 notify constrained 1 s sess 145 Ch utor aste fedi atate aoe ee aerate atest 85 Ht Ao essent Retina tea boa toa eta TE PUER 85 nth clause 3 5 2 4 1211RDLBPUTPIBS GRIS 56 nth recorded 3 lg vu de AES 59 ENOL DE o uad eae Rep CUR UR UA aree nee 85 nito 85 EIDEL AAA ee seat de agere dd 32 number tom 2 42 095 54 0 FA dwell eines 34 ninber CHars 2 mies eid ee EVE 39 number c des 2 m Reis emi uas 34 number to chars 2 essen 93 number to chars 3 eee 93 YAP Prolog User s Manual numbervars 3 ees 34 O on cleanup 1 suuersvnvesasta ness Perm sea 98 oncsignal 3 akser seende er TRUE 66 Once 1 2 55 lb la eee PII eA PS 30 py EE 79 OpenA3 iescecRReAPRS eue PE Rd xU tered 40 Open 4 omis n ERE TT D EE Lee neta ee 41 open chars stream 2 esses 93 ord add element 3 esee 86 ord del element 3 eese 86 ord disjoint 2 eee kr eR rSn 86 ord insert I iairideleaiirdesterieeenetss 8T ord intersect 2 c c lr Rhe ees 8T ord intersect 3 EE 8T ord list to ASSOC Dic is dace ereptus 83 ord member 2 e EE Lbeemreeisewcue seris 86 ord seteq 2 Lolo Rev vena beer eps 8T ord setproduct 3 u colsle dede bee 8T ord s ubiract 3 J cer err d 8T E elu Bid ere part de 8T
89. actall l 1c eine pedsek anita dues daterer 56 EEN 62 statistics O holes eem rte PU E dU De balle 72 Sabse die EE Riek Se ods 72 U unknown cde Ae eh eg 31 V Version EET 80 Chapter 23 Compatibility with Other Prolog systems 203 23 2 4 Yap predicates not available in SICStus Prolog These are YAP built ins not available in SICStus Prolog GE 35 A add to array element 4 u unnnrnnrnrrnne 71 FECTS MB rr EENS 65 Ir MN TEMERE 62 alwans Drompt user 00sec eee e ee eee 52 GEESS bakre dabas 70 array element 3 Ae dE Eed 71 assert stallo 1 Ae boe e LP Ele d peneste 55 asserta static T sess ans Le abe 55 ssertz static 1 ues eI debuerit SE 56 atom concab 2 icone de RE dag dia ed 33 atorm coticab 9 ck e oea SEERNE ERE SES SE FEJES SENEST ESS 33 EES ER E EE ER avl 160 kup 3 d e te sd deeg d dE ER C call count data 0 c p05 SEENEN EE 68 call count data 8 sies este cee 68 callcwath args 1 i dee ee A ER aad 29 dA 30 TI MM 64 heelen waned whale E 81 checknodes 3 is cte srt enden kien AR ERR 81 Close static aal 71 compile 1 directive sesi crcersicresi vissers 19 compile ecpressions esee eese 20 Consult EE 19 EE 81 current_prolog_flag 2 0 0 e eee iei 79 D delete 8 seii RE sak ed REDI ADAE weaned 89 do not compile expressions 0 20 denamie Dredicate uun usenrreerrrre 55 E eraseall l i nents ieee geen REX RE eae te 59 CXIStS EE 52 EE 20 ge
90. al 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 with 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 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 gec 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
91. alk 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 For the latest news please see the URL http www logtalk org 160 YAP Prolog User s Manual Chapter 15 Parallelism 161 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 T his 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 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
92. and eventually results in linear expressions Chapter 12 CLP Q R Manual 121 clp q fexp X Y 1 2 3 X X Y Y nonlin Y 2 X 2 2 Y X 2 X 2 1 0 Equating X and Y collapses the expression completely and even determines the values of the two variables clp q fexp X Y 1 2 3 X X Y Y X Y X 1 4 Y 1 4 12 11 Isolation Axioms These axioms are used to rewrite equations such that the variable to be solved for is moved to the left hand side and the result of the evaluation of the right hand side can be assigned to the variable This allows for example to use the exponentiation operator for the computation of roots and logarithms see below A B C Residuates unless B or C is ground or A and B or C are ground A B C Residuates unless C is ground or and B are ground X min Y Z Residuates unless Y and Z are ground X max Y Z Residuates unless Y and Z are ground X abs Y Residuates unless Y is ground X pow Y Z X exp Y Z Residuates unless any pair of two of the three variables is ground Example clp r 12 pow 2 X X 3 5849625007211565 clp r 12 pow X 3 585 X 1 9999854993443926 clp r X pow 2 3 585 X 12 000311914286545 X sin Y Residuates unless X or Y is ground Example clp r 1 2 sin X X 0 5235987755982989 122 YAP Prolog User s Manual X cos Y Residuates unless X or Y is ground X tan Y Residuates unless X or Y is
93. ap flag 2 option 74 char c nversion 2 4 2 b Rl ed dae sel 44 character escapes yap flag 2 option 74 Checklist 2 2 0 echote sos ue aer debtor de EE Tas 81 Checknodes 3 EE 81 chr debug 0 sese rebrebbe acre eR ERE Te 149 chr debugging O s ite eee tte D eR rS 149 chr leash 1 Mere E ebe ise 149 chr nodeb g 0 EE 149 chr nospy i1 ueesexretrenre ree Eee We 151 chr notrace 0 1221 1bBIc weed nep 149 chr ospy d eee bee deed Rp erI PE uera re 150 Chr Ltrace 0 4 22 ls ei IS dat anne re 148 Clausa 2 culo SAKE epa E ems a IM eae vts 56 clause 3 l2 eR EPIS Phas eee et 56 cleanup all 0 e e eee pP eset 98 uberi PRETI 41 ak 41 close static array 1 sess sss 71 compare 3 cea EN lle hele ego 35 compile 1 erbe RD Ue EIE E 19 compile erpressionse 20 complement 2 eas das reped 101 comnpose 3 od exe eS hash deeds 102 comnpound 4 i naar edes ese e bb adus 32 consult 1 1 e osa retour A men 19 convlist 3 e eed es DR break inis 81 copy term 2 2 Bb ede ne eee eee as 35 cputime statistics 2 option 73 create mutablae 9 4 1 22 39 e ANTA 67 current atom 1 bb DELLI AS 57 current char conversion 2 45 current constraint 2 illas ii 144 Current handladr 2 s duele tod aS 144 current inp t 1 2 2 e RR e meh se 42 current key 2 i9 5 1 4 Aedes indus 59 current mod le 4 Ae 525 29 2 dees ae nsi 72 cirrent modile 2 Aere ch des decease age het 72
94. ape character Escape sequences were not available in C Prolog and in original versions of YAP up to 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 gt solo character atom gt lower case letter name character atom gt symbol character atom gt single quote single quote atom gt atom quoted characters atom quoted characters gt 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 o5 lt symbol character gt denotes one of amp eEx 1 i lt 70N 7 lt lower case letter gt denotes one of a Z lt name character gt denotes one of EA OE AR 022 9 lt single quote gt denotes S 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 12 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 Chapter 3 Syntax 17 3 2 4 Variables Variables are described by lt variable starter gt lt variable character gt where lt variable starter gt denotes one of _A Z lt v
95. ar you can just type Return to creep or single step into your program You will notice that the CHR debugger stops at many ports If this is not what you want the predicate chr leash gives full control over the ports at which you are prompted Chapter 13 Constraint Handling Rules 149 chr debug Switches the CHR debugger on and ensures that the next time control enters a CHR port with a spy point set a message will be produced and you will be asked to interact chr nodebug Switches the CHR debugger off If there are any spy points set then they will be kept chr notrace Equivalent to chr nodebug chr debugging Prints onto the standard error stream information about the current CHR de bugging state This will show 1 Whether the CHR debugger is switched on 2 What spy points have been set see below 3 What mode of leashing is in force see below chr leash 4 Mode The leashing mode is set to Mode It determines the CHR ports at which you are to be prompted when you creep through your program At unleashed ports a tracing message is still output but program execution does not stop to allow user interaction Note that the ports of spy points are always leashed and cannot be unleashed Mode is a list containing none one or more of the following port names call Prompt when a constraint is executed for the first time exit Prompt when the constraint is successfully processed i e the ap plicable rules have ap
96. arameters 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 actually 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 in
97. arbage collect forces a garbage collection garbage collect atoms The goal garbage 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 Dy 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 hand
98. 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 61 7 81 L2 L 1 2 3 4 5 6 7 8 no Chapter 7 Library Predicates 85 is list List True when List is a proper list That is List is bound to the empty list nil or a term with functor and arity 2 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
99. ariable character gt denotes one of 8 Z A Z If a variable is referred only once in a term it needs not to be named 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 ES TK SG 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 sam
100. arr deeg hee ae ket 67 E EE 49 Eet0 2 EE LE de RERO eU PIRE 50 getrand l Age E e VELO NER EU 89 gtound l s cee ee irea ERE REDE e RE Nd 34 H halt 0 EEE 30 halt l bc den aens t reed iere deg 30 h ad gege oorr teh braket esgete 88 h ap 8126 2 yi renses aF TE ORIS 84 heap to lisb 2 revo bn REPE ERU 84 host id I Lasses badene 95 host name 1 oec EROR hie bei keds 95 I D RER EET ETTE TERE ENES 29 InCOTe l i bare RR XE ERI RIDES 29 mitializationyQ eec dee ree DERE Rd 80 mesen eet Mati done eck ve eee 32 18 Dewi p ER 39 EE 85 isztn t ble L sc cobre ato reote s 67 J join quetie 93 esr httegted eco E 88 jump_queuve 3 ke erik ee eee 88 K Keysort 2 Ee piot oE See E RE RD 36 RE EDER EE 95 200 L EE ode ten PEE GF C SERA 85 leash o bisebtuenee eee Mp ER E RIAM S 169 length 2 gege AE dee Ee 36 length queue 2 erri e obere b EHE Ee 88 list jora queue 3 Eed dukkene ne 88 list jump queue 3 sseseee enn 88 list to dssoc 2 A tie bete edid Leto dedu edes 83 hist io heap 2 v sse sore e RIS RA RES 84 list to ord set 2 Ae de b sepe d 86 list to queue 2 ere NEEN ses 88 list to tree 2 see EES 99 hsting l si operai oaov ae lode ees 56 M m ke directory 2 ai d it 95 take queue T sei p bie DA Re sees 88 inap assoG6 S ses rese iprit ne rob digg 83 imapctree 3 fantes deres rede 99 Member E ned Reder Ar den 85 memberchk 2 vrsseskyige araveedeidergedae es
101. art 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 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 X Y X raised to the power of Y from the C Prolog syn
102. as a box with control flowing into and out of that box In the four port model control is caught at four key points before entering the procedure after exiting the procedure meaning successful evaluation of all queries activated by the procedure after backtracking but before trying new alternative to the procedure and after failing the procedure Each one of these points is named a port Call Exit gt descendant X Y offspring X Y descendant X Z amp offspring X Y descendant Y Z 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 3
103. ation main main write Hello World nl The initialization directive tells Yap to execute the goal main after consulting 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 C usr bin yap L H main main HIT write H n1 main T unix argv AllArgs main 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 C usr bin yap L main main HIT write H n1 main T unix argv AllArgs main AllArgs J The indicates the next arguments are not for YAP Instead they must be sent directly to the argv builtin 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 describ
104. 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 dec10 Report the syntax error and retry reading the term fail Report the syntax error and fail default error Report the syntax error and generate an error quiet Just fail 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 G If bound set G 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 78 YAP Prolog User s Manual 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 proce
105. ber Generator The following random number operations are included with the use module library random command Since Yap 4 3 19 Yap uses the O Keefe public domain algorithm based on the Applied Statistics algorithm AS183 getrand Key Unify Key with a 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 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
106. ble 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 e lt if X precedes Y in the defined order e if Y precedes X in the defined order 36 YAP Prolog User s Manual 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 Y fails but X Y X Y succeeds X 2 fails but X22 X 2 succeeds X Y ISO Terms X and Y are not strictly identical X e 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 order X 0 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 k
107. blem discussed in see Section 12 12 Numerical Precision and Rationals page 122 Chapter 12 CLP Q R Manual 133 The Monash University clp R interpreter features a dump n predicate It is used to print the target variables according to the given ordering Within this version of clp Q R the corresponding functionality is provided via ordering 1 The difference is that ordering 1 does only specify the ordering of the variables and no printing is performed We think Prolog has enough predicates to perform output already You can still run the examples referring to dump n from the Prolog toplevel clp r expand library Cclpqr examples monash mortgage noexpand go2 A clp r mg P 120 0 01 0 MP dump P MP P 69 7005220313972 MP go3 clp r mg P 120 0 01 B MP dump P B MP P 0 30299477968602706 B 69 7005220313972 MP go4 hh clp r mg 999 3 Int 0 400 dump nonlin _B _B Int A 400 0 0 0 nonlin _A _A Int 400 0 0 0 _B 599 0 999 0 Int 12 21 A Mixed Integer Linear Optimization Example In this section we are going to exercise our solver a little by the computation of a small mixed integer optimization problem MIP from miplib a collection of MIP models housed at Rice University Here are the original comments on the example NAME flugpl ROWS 18 COLUMNS 18 INTEGER 11 NONZERO 46 BEST SOLN 1201500 opt LP SOLN 1167185 73 SOURCE Harvey M Wagner John W Grego
108. ce 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 7 K Defines the relation K is a currently defined database key whose name is the atom A It can be used to generate all the keys for the internal data base key statistics K Entries Size Returns several statistics for a key K Currently it says how many entries we have for that key Entries and what is the total size spent on the key Size 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 A C Associate atom 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 60 YAP Prolog User s Manual Valuei is Valueti set value counter Value1 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 las
109. ckets 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 57 6 8 Internal Data Base 58 6 9 The Biackboard cnc ne 61 6 10 Collecting Solutions toaGoal eee eee eee 61 641 Grammar Rules 2i a eee eae keene 62 6 12 Access to Operating System Functionality 64 6 13 Term Modification 66 6 14 Profiling Prolog Programs creu pssaisesn risasi pasaian 67 6 15 Counting Call 68 0 10 JArrAyS cereis et Rn be n E i PUPURETI C perd ERR 69 6 17 Predicate Information 71 6 18 Miscellaneous ccs aos re oe ates ace eee len be 72 7 Library Predicates e 81 T l Apply Macros sea sa sk bol ret aU nd God EG A etn 81 7 2 Association Liste 82 7 3 AVL rees 83 CA JIleapB iissetewsereervuuso neri dens QR he ERIS 83 7 5 List Manipulation ccce htec tse oat e 84 7 6 Ordered Hetz 86 7 7 Pseudo Random Number Integer Generator 87 CB QUCWCS end epe d ied n edge Tu ed ooo End ae ned 88 7 9 Random Number Generator 88 7 10 Red Black rees 89 7 11 Regular Fapresgions esses essen 89 1 12 Splay LEGS cess ea kan tee eo eoe ween Eee t Re 91 7 13 Reading From and Writing To Strings 92 7 14 Calling The Operating System from YAP 94 7 15 Utilities On Terms ee add ke sele 97 7 16 Call With regist
110. compute primes simply as for variations see the handler primes p1 use module library chr handler eratosthenes constraints primes 1 prime 1 primes 1 lt gt true primes N lt gt N gt 1 M is N 1 prime N primes M generate candidates absorb J 0 prime I prime J lt gt J mod I 0 true The constraint primes N generates candidates for prime numbers prime M where M is between 1 and N The candidates react with each other such that each number absorbs multiples of itself In the end only prime numbers remain Looking at the two rules defining primes 1 note that head matching is used in CHR so the first rule will only apply to primes 1 The test N gt 1 is a guard precondition on the second rule A call with a free variable like primes X will delay suspend The third multi headed rule absorb J reads as follows If there is a constraint prime I and some other constraint prime J such that J mod I 0 holds i e J is a multiple of I then keep prime I but remove prime J and execute the body of the rule true 13 3 CHR Library CHR extend the Prolog syntax by a few constructs introduced in the next sections Technically the extension is achieved through the user term expansion 2 mechanism file that contains a constraint handler may also contain arbitrary Prolog code Constraint handling rules can be scattered across a file Declarations and options should precede rules There can only b
111. cond 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 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 file exists File Permissions The atom File corresponds to an existing file with permissions compatible with Permissions YAP currently only accepts for permissions to be described as a number The actual meaning of this number is Opera
112. cument is an instance of the general Constraint Logic Programming scheme introduced by Jaffar amp Michaylov 87 The implementation is at least as complete as other existing clp R implementations It solves linear equations over rational or real valued variables covers the lazy treatment of nonlinear equations features a decision algorithm for linear inequalities that detects implied equations removes redundancies performs projections quantifier elimination allows for linear dis equations and provides for linear optimization The full clp Q R distribution including a stand alone manual and an examples directory that is possibly more up to date than the version in the SICStus Prolog distribution is available from http www ai univie ac at clpqr 12 2 Referencing CLP Q R When referring to this implementation of clp Q R in publications you should use the following reference Holzbaur C OFAI clp q r Manual Edition 1 3 3 Austrian Research Institute for Ar tificial Intelligence Vienna TR 95 09 1995 12 3 CLP QR Acknowledgments Acknowledgments The development of this software was supported by the Austrian Fonds zur Foerderung der Wissenschaftlichen Forschung under grant P9426 PHY Financial support for the Aus trian Research Institute for Artificial Intelligence is provided by the Austrian Federal Min istry for Science and Research 116 YAP Prolog User s Manual We include a collection of examples that has be
113. cute 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 timeout command time out Goal Timeout Result Execute goal Goal with time limited Timeout where Timeout is measured in milliseconds
114. d bindings options are still around but there are CHR syntax extensions Section 13 3 3 CHR Syntax page 140 and pragmas Section 13 3 5 CHR Pragmas page 142 offering better grained control 4 The Eclipse library of CHR provided automatic built in labeling through the label with declaration Since it was not widely used and can be easily simulated built in labeling was dropped The same effect can be achieved by replacing the dec laration label with Constraint if Guard by the simplification rule chr labeling Constraint lt gt Guard Constraint chr labeling and by renaming the head in each clause Constraint Body into Constraint Body where Constraint is a new predicate Efficiency can be improved by declaring Constraint to be passive chr labeling Constraint Id lt gt Guard Constraint chr labeling pragma 158 YAP Prolog User s Manual passive Id This translation will not work if option already in heads on In that case use e g chr labeling Constraint lt gt Guard Constraint chr labeling to make the new call to chr labeling differ from the head occurrence The set of built in predicates for advanced CHR users is now larger and better designed Also the debugger has been improved The Opium debugging environment is not available in SICStus Prolog Chapter 14 Logtalk 159 14 Logtalk The Logtalk object oriented extension is available once included with the use module library logt
115. d 49 put ch r 2 ette seeker E ERE ERIRE 50 put code 1 sans sedlene Des bien IMS 49 OC 50 put lab l A4 geolo EOD ske leeks 99 putenu 2 4 ep pe UII MR HEN ehe 64 Q queue to li8t 2 0 n Lr IER takii e 88 R random 423400234 AEN De See eee ees 89 ER EE 89 randsed 3 iste er BELL apa 89 randset 3 i v ve ROI Rd eR ARE RN EET 89 Tanmnimn 1 o2 sadel e be med 87 r nsStart 0 0 4 we ales age de dn Gua baie ae 88 ranstart 1 EE 88 r nunif 2 wee ed ud e Ares 88 re ach ble 3 fi jad RRSER REPLIES 102 E KEE 44 Pead 2 iss d xor ES Dota eU 50 read from chars 2 eese 93 read term 2 se e ber re ERREUR Rd 44 read Lerm sees nee 50 reconsult 41 4 52 22 pa S08 depend ue 19 recorda 37 5 caa s v dys eid dues atira REA 58 recorda at S3 isi RP E EO neds 58 recordadjfnot 3 3 2i 2p pe iden RE e p 58 60 r corded 3 se esse ek ee dd co PEE E ada 59 recordz 3 i iae dau ek ga pe Ree PEG 58 recordz at 3 i de SES PIER 58 recordzifnot 3 2 odios EE un 60 regexp 3 ic cec dea weer ris um Yu de eps 90 e olco ne tel Reed dE be 90 remove constraint 1 csse 145 remove duplicates sess eee 85 remove from patbh l eee 21 he GN 4 ot v ERG ee ere RP MUNERE 64 rename file 2 occa crt Pr e 95 LEM OE TUER 28 reset op Counters se eee eeee 167 resize static array 3 sss T Te6StOre 1 i Ee eR ae ate Que 22 retr act 1 live RV e dei dS 56 retract 2 Sed E
116. d ees 50 Wibe t chars 2 aars bbs d der needa eee ty 92 write to chae 020i ri ee RR E Yu 93 EE 45 KEE 50 202 YAP Prolog User s Manual 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 KK os nb Rd RR AUR BRE ER CURRERE 19 VE Q 19 A abolisli Did cese tetas a ete Amgen SE 55 ADOMSH 2 5 te Cem 55 Assent EE 55 c gp Em 57 asserta Locus beseicue gute ed SUERTE Rd 55 c D pm PRX 58 E NEE 55 ASSELS Cm 58 Sabotage ae REECH 33 B EE 62 C Glas tt ae LSE SO SE ESS PE ber 56 CAUSE Bis eege reg redan br hed 56 ul m 41 D deDug D soc etes emet pada PROSE 169 e 54 E erase OE SES SEE y I Re A 59 erased T stam tid edad ee vede Dice pbi 59 F forni bt 2 ves rrt oti tee P p 46 format S cile gd tipii geed PRO Pes 48 I Instance 2 cese tiere tate dtes uda Se 59 L TiStin ge O i405 he ee E REES 56 N ithclause 3 2562 Ae AE Ae poeti 56 nth recorded 3 ie cernere peak rh s 59 number charg 2 sc vei sens weet ieee ds 33 Ope d naa eR CRF HOA EUH Ee he 41 P predicate_property 2 000 cee eee 57 Drolog mitialzation 80 R read term 2 sis crx Ee SE A UA 44 read term EE 50 E EE 58 recordaifnot 8 cere teer ER He eR 58 recorded 3 EE 59 EE eer g dae arenas ss 58 rettact l uos iroko iici inneir Sadssdne art 56 rettact 2 Seege jente alfa 58 retr
117. d for that property If the guard succeeds the rule applies Otherwise the next rule is tried If the firing CHR is a simplification rule the matched constraints are removed from the store and the body of the CHR is executed Similarly for a firing simpagation rule except that the constraints that matched the heads preceding V are kept If the firing CHR is a propagation rule the body of the CHR is executed without removing any constraints It is remembered that the propagation rule fired so it will not fire again with the same constraints if the constraint is woken and reconsidered If the currently active constraint has not been removed the next rule is tried If the current constraint has not been removed and all rules have been tried it delays until a variable occurring in the constraint is touched Delaying means that the constraint is inserted into the constraint store When a constraint is woken all its rules are tried again This process can be watched and inspected with the CHR debugger see below 13 3 5 Pragmas Pragmas are annotations to rules and constraints that enable the compiler to generate more specific more optimized code pragma can be a conjunction of the following terms already in heads The intention of simplification and simpagation rules is often to combine the heads into a stronger version of one of them Depending on the strength of the guard the new constraint may be identical to one of the heads to rem
118. d 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 5Set1 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 insert 3 ord del element Set1 Element Set2 Removing Element from Set1 returns Set2 ord disjoint Set1 Set2 Holds when the two ordered sets have no element in common ord member Element Set Holds when Element is a member of Set Chapter 7 Library Predicates 87 ord insert Set1 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 Set1 Set2 Intersection Holds when Intersection is the ordered representation of Set1 and Set2 ord seteq Set1 Set2 Holds when the two arguments represent the same set ord setproduct Set1 Set2 Set If Set1 and Set2 are ordered sets Product will be an ordered set of x1 x2 pairs ord subset Set1 Set2 Holds when every element of the ordered set Setl appears in the ordered set Set2 ord subtract Set1
119. d 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 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 of file Further reads from of the same stream may cause an error failure see open 3 read term T 0ptions 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 ta
120. date semantics leashing mode style checking handling calls to undefined procedures how directives are inter preted when to use dynamic character escapes and how files are consulted ISO Read only flag telling the maximum arity of a functor Takes the value unbounded for the current version of YAP 76 YAP Prolog User s Manual 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 multiprecision library If bounded is false requests for max integer will fail 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 multiprecision library If bounded is false requests for min integer will fail 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 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 redefine warnings If Value is unbound tell whether warnings for procedures defined in several diffe
121. dde EE doe E Es 36 SOUPCE 0 5 35 3 4 aret E to Dice er ede need 19 source mode 29 i i BERG uu wee auc ds 19 Splay access D c iii sin Rd prd eed 92 splag deleteii 00 cece eee 92 Splay nrt43 muss sonrie pupa WU panes Ms els 92 splay insert 4 iius idea e da 92 Splay join 3u s eese RE ease ke dnne 92 Spl y split b EE 92 SPY PET 169 SDy wrlte 2 i Se DO AE hada 170 srandom i e vd gett dE Ar 40 stack dump on error yap flag 2 option 77 stack shifts stack shifts 3 option 73 start low level trace 0 165 static array S s eoenb Ri uv pesce Peg 70 71 static array properties 3 70 214 static array to term 3 ss 70 statistics l iiisdle m e eis E robes ES 72 statistics 2 Re ere EE A K stream Drobertu sse enn 42 Stream sS lecbt 3 2 2 xo edem Rs 42 strict iso prolog flag 2 option 76 Style check 1 cc e cede rn pase esker 21 sub atom B lese en 34 s b edges 3 oec narre Dee Eu 101 S blisSt 2 va ane danker Aden puesta 86 su bsumes 2 oo needa d HEEN addu Sr p ar dada 97 Subsumes chk 2 shoei AE 97 Suffix 2 4 4 red beige Es 86 sum 138672 oe ceeded eed Headset aioe 86 sumargs 4 s a RR pu Rex te RR edes 81 su mlist 2 i as bya eee PPO RE Es 86 Sumlist 4 2 p 9 m3 p PA sacar hd et Mtoe 81 sumnodes 4 1 0 ccc ccc cee teens 81 syntax errors yap_flag 2 option 77 syntax errors 1 read term 2 option
122. der EEN page decus 30 I MEDI D PEE 59 Int ger 1 ius ceret esed REED ahd SP Paus 32 K Keysort 2 dE MEA ERE OnE eis 36 L leash T ete rats es ferder herres 169 length 2 coire RR EU RERO Eed ER 36 N noorjpH an 92 EENS 50 nodebug 0 ss Sivas Hebd ded etes ove kake 169 nofileerrors 0 Eeer 52 nion NETTE 32 NOSPY Lucre see dota vn eee ae 169 nob 1 4liebxYoce ER I YR HAERES ene 28 pumber Toscani AE Me DRM 32 O TEE 79 Chapter 23 Compatibility with Other Prolog systems 191 P Primitive EE 32 puni loizi tenbei pee ele eese iR OUS RAN 46 Prom pt 2 cbe redi nini ep epe d wg aedes 79 PU Ling EE 48 R POAC Lirispardanadlerdedagereke rare deles 44 TeCconsult EE 19 recorda 3 i sek iin E We gadd oP eden 58 recorded 3 sts menti tieteneb ewti ees nk 59 recorndz 9 par barske eee ERI OUS 58 rename 2 ooa orat e rns Lene PPP E 64 xepeat Q ve dace taka epa PRI ENEE 28 S GEN ett pa aaa Sede EEE 22 See I xe cios ENE pii seis Papa 44 seeing Lekse ione kanal de 44 ENEE 44 SeboL 3 gett EE RR Pero bores 62 3s P 64 SKIP Ae s eieitensrcePheLnE tema bad VIRA RII des 49 SOUL oc eo bti PO Ehe OE rea bie 36 SPY LL depot Bit contd dee ER 169 Stabistics O aarneskinterm RI e e sette by T2 system 1 EE 64 T ERE 50 EE RE 43 tellng l sueisi generere ERES pure LEY Ped 43 term espansion sees 63 Meer 43 eV des 27 V Val lite thet esker EE EP ee bees 32 KAN EEE rine Pee ES ES bys 4
123. distribute modified versions of this chapter under the conditions 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 chapter into another language under the above conditions for modified versions except that this permission notice may be stated in a translation approved by LMU Copyright 1996 98 LMU Ludwig Maximilians University Munich Germany e The CLP Q R package developed at OFAI Austrian Research Institute for Artificial Intelligence by Christian Holzbaur The package is distributed under the OFAI license Documentation on this package is a chapter of this manual which is covered by the OFAI license Copyright c 1992 1993 1994 1995 OFAI Austrian Research Institute for Artificial In telligence OFAI Schottengasse 3 A 1010 Vienna Austria 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 conditions 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 language under the above conditions for modified
124. 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 void YapPutValue Atom at Term value Associate the term value with the atom at The term value must be a constant This functionality is used by YAP as a simple way for controlling and communicating with the Prolog run time Term YapRead int void GetC Parse a Term using the function GetC to input characters int YapRunGoal Term Goal Execute query Goal and return 1 if the query succeeds and 0 otherwise int YapRestartGoal void Look for the next solution to the current query by forcing YAP to backtrack Chapter 22 Using YAP as a Library 187 int YapReset void Reset execution environment similar to the abort 0 builtin This is useful when you want to start a new query before asking all solutions to
125. ds 61 bb update 3 secs herr REP RR eS 61 break O DEED 30 C E tere 64 EE BESS peas 29 call cleanup 1 suse rer REIR ee Res 98 Calls eleanup fr ere ied ees 98 Call reegen EE dE temere ERR 107 c llable 1 ec three EEN 32 char o ee RIA Mene we Hn bende ri 34 char comversgion sese 44 el E E ox nace sacle b t Roue 98 di uM Cmm 41 oup n 35 compile 1 ney os See rub de ean hib s 19 complement 2 eve rdnee eitow ve ER 101 COMPOSE EE 102 compound 1 22445038 secus nit ikp eme Ee FU 32 copy term La visite benc dende dei enke UR 35 Chapter 23 Compatibility with Other Prolog systems 199 create mutable 2 i c ehm ER 67 Current atom Ae asa PR Rp 57 current char conversion 2 45 current imput EE 42 current key 2 Aa PERRA PO PRI AER 59 current inodule 1 Ae ber eerte RR 72 Current module 2 NEEN messer dk 72 current 0p 3 err RI EN IHRER ROREM 79 Curr ntoutput L se eprrsstirensdkeerettsrelee 42 Curtent Dredicate 57 current predicat 2 o oecsciiccrrirnseriirsrers 57 current siream 3 cg see bxEeRnR a anaa 42 cyelio term l ud ieri de iara REV 97 D Gabe is eege ea treat e TE EEE 94 db xeference d ae e A PETER 32 debugging 0 edv exea ees d de ret rx 169 del vertices 3 i eim b BEER RE PY 100 delete 8 i scc roi tes e Ru wane RR EE 84 delete Mel user crue krins sant 94 delete hile 2 iet sere bet IER E etre 94 T TOR 107 directory files 2 acces desee ee 9
126. dures 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 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 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 user input 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 Chapter 6 Built In Predicates 79 By default the user input stream is set to a stream corresponding to the Unix stdin stream user output 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 strea
127. e e 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 amp ARG1 amp t which is nowadays d YAP Unify ARG1 t e cut fail and cut succeed are now functions e The use of Deref is deprecated All functions that return Prolog terms including the ones that access arguments already dereferenciate their arguments e 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 184 YAP Prolog User s Manual Chapter 22 Using YAP as a Library 185 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 1 To actually use this library you must follow a five step process You must initialize the YAP environment A single function YAP_FastInit asks for a contiguous chunk in your memory space fills it in with the data base and sets up
128. e 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 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 Chapter 6 Built In Predicates 41 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 write or append the file is not writable open F M S Opts ISO 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 reposi
129. e 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 YAPSRCVOPT Yap directory to the Project s Source Files use FileView add all h files in the YAPSRC H directory YAPSRONinclude directory and in the YAPSRC OPTYap 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 YAPSRC VC include 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 YAPSRCNOPTYap and YAPSRC include The syntax is YAPSRC H YAPSRC VC include YAPSRC OPTYap YAPSRCV include Build the system should generate an yapdll dll and an yapdll lib Copy the file yapd11 d11 to your path The file yapd11 1ib should also be copied to a location where the linker can find it Chapter 1 Installing YAP 7 Now you are ready to create a console interface for Yap 1 create a second project say wyap with File New The project will be a WIN32 console projec
130. e achieved with corresponding pragmas see Section 13 3 5 CHR Pragmas page 142 The remaining options are meant for CHR implementors only option flatten on off option rule ordering canonical heuristic option simpagation scheme single multi option revive scheme new old option dead code elimination on off 13 3 7 Built In Predicates This table lists the predicates made available by the CHR library They are meant for advanced users who want to tailor the CHR system towards their specific needs current handler Handler Module Nondeterministically enumerates the defined handlers with the module they are defined in current constraint Handler Constraint Nondeterministically enumerates the defined constraints in the form Functor Arity and the handlers they are defined in insert constraint Constraint Id Inserts Constraint into the constraint store without executing any rules The constraint will be woken and reconsidered when one of the variables in Con Chapter 13 Constraint Handling Rules 145 straint is touched Id is unified with an internal object representing the con straint This predicate only gets defined when a handler and constraints are declared see Section 13 3 2 CHR Declarations page 140 insert constraint Constraint Id Term Inserts Constraint into the constraint store without executing any rules The constraint will be woken and reconsidered when one of the variabl
131. e as consult F F The same as reconsult F Example file1 file2 file3 file4 will consult filei file4 and 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 1oaded 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 1oaded 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 20 YAP Prolog User s Manual The same as source
132. e at most one constraint handler per module 13 3 1 Loading the Library Before you can load or compile any file containing a constraint handler solver written in CHR the chr library module has to be imported use module library chr 140 YAP Prolog User s Manual It is recommended to include the corresponding directive at the start of your files con taining handlers use module library chr 13 3 2 Declarations Declarations in files containing CHR affect the compilation and thus the behavior of the rules at runtime The mandatory handler declaration precedes any other CHR specific code Example handler minmax A handler name must be a valid Prolog atom Per module only one constraint handler can be defined The constraints must be declared before they are used by rules With this mandatory declaration one lists the constraints the rules will later talk about The declaration can be used more than once per handler Example constraints leq 2 minimum 3 maximum 3 The following optional declaration allows for conditional rule compilation Only the rules mentioned get compiled Rules are referred to by their names see Section 13 3 3 CHR Syntax page 140 The latest occurrence takes precedence if used more than once per handler Although it can be put anywhere in the handler file it makes sense as with other declarations to use it early Example rules antisymmetry transitivity To simplify the hand
133. e 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 Theunification algorithm calls the user defined predicate verify attributes 3 before trying 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 11 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 dec
134. e 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 2 5145 LT 69 L1 7 L1 85111 vertices Graph Vertices Unify Vertices with all vertices appearing in graph Graph In the next example vertices 1 3 5 2 4 3 1 4 51 5 1 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 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 4 5 5 1 6 1 7 1 8 11 0 2 9 10 11 NG NG 0 17 5 5 2 4 3 1 4 51 5 L Gel 7 13 8 11 99D 30 D 31 1 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 NL 3 01 4 51 5 1 6 L 7 6 8 11 Chapter 7 Library Predicates 101 add edges Graph Edges NewGraph Unify NewGraph with a new graph obtained by adding the list of edges Edges to the graph Graph In the next example add edges 1
135. e 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 Source true if source for the predicate is available number of clauses ClauseCount Number of clauses in the predicate definition Always one if exter nal or built in 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 58 YAP Prolog User s Manual 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
136. e guard if present from the body of a rule Since is read as disjunction by the reader care has to be taken when using disjunction in the guard or body of the rule The top level disjunction will always be interpreted as guard body separator so proper bracketing has to be used e g a lt gt b c d e instead of a lt gt b c d e and a lt gt true d e instead of a lt gt d e In simpagation rules separates the heads of the rule into two parts Individual head constraints may be tagged with variables via which may be used as identifiers in pragma declarations for example Constraint identifiers must be distinct variables not occurring elsewhere in the heads Guards test the applicability of a rule Guards come in two parts tell and ask separated by amp If the amp operator is not present the whole guard is assumed to be of the ask type Declaratively a rule relates heads and body provided the guard is true A simplification rule means that the heads are true if and only if the body is true A propagation rule means that the body is true if the heads are true A simpagation rule combines a simplification and a propagation rule The rule Heads1 Heads2 lt gt Body is equivalent to the simplification rule Heads1 Heads2 lt gt Heads1 Body However the simpagation rule is more compact to write more efficient to execute and has better termination behavior t
137. e 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 When T is not instantiated F and N must be If N is 0 F must be an atomic symbol which will be unified with T If N is not 0 then F must be an atom and T becomes instantiated to the most general term having functor F and arity N If T is instantiated to a term then F and N are respectively unified with its top functor name and arity Chapter 6 Built In Predicates 35 In the current version of YAP the arity N must be an integer Previous versions allowed evaluable expres
138. e of a functor followed by arguments eg a b the same as a b of arity one versus a b the same as 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 integer lt digit gt lt single quote gt 0 xXo lt alpha numeric char gt where 1 stands for optionality optional repetition one or more times digit 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 of an integer token can not be immediately followed by one of the characters ei E or Followi
139. e 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 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 told The current output stream is unified with S 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 44 see 5 seeing S seen YAP Prolog User s Manual If Sis acurrently 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 associate
140. e the absolute value of last term is an upper bound on the error from file library C clpqr examples root e N E Err exp 10 N 2 Half 1 2 inv e series Half Half 3 Err Inv E E 2 2 1 Inv E inv e series Term SO Err Sum abs Term lt Err 50 Sum inv e series Term S0 N Err Sum 124 YAP Prolog User s Manual Ni is N 1 Termi Term N S1 Term1 S0 inv e series Termi S1 N1 Err Sum The computation of the rational number E that approximates e up to at least 1000 digits in its decimal expansion requires the evaluation of 450 terms of the series i e 450 calls of inv e series 5 clp q e 1000 E E 714905622893276021366680959207 2842334290744221392610955845565494 370875022946776173047173889519779227 1346693089326 102132000338192 0131874187833985420922688804220167840319199699494193852403223700 5853832741544191628747052136402176941963825543565900589161585723 4023097417605004829991929283045372355639145644588174733401360176 9953973706537274133283614740902771561159913069917833820285608440 3104966899999651928637634656418969027076699082888742481392304807 9484725489080844360397606199771786024695620205344042765860581379 3538290451208322129898069978107971226873160872046731879753034549 3130492167474809196348846916421782850086985668680640425192038155 4902863298351349469211627292865440876581064873866786120098602898 879913009887737209736006593482775112065921347052
141. e 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 numbers database references atoms Chapter 21 C Language interface to YAP 177 pairs lists compound terms The primitive YAP Bool YAP IsVarTerm YAP Term t returns true iff its argument is an uninsta
142. e 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 174 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 cut would be needed to prevent some possible uses for the procedure like generating all logicians In this situation the indexing mechanism generates instructions that implement a search table In this table the value of the first argument would be used as a key for fast search of possibly matching clauses For the query of the last example the result of the search would be just the fourth clause and again there would be no need for a choice point If the first argument is a complex term
143. e the syntax of YAP at two levels We first will describe the syntax for Prolog terms In a second level we describe the tokens from 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 gt 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 gt subterm 1200 list string number atom variable subterm 999 subterm 999 arguments tT 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 cas
144. eam Droberta ne 42 Sstylech ck Wi is eced elek 21 sub atorm B siu oh chet cee hide tereni PE det 34 EE 86 Suniarps 4 e l p dh ea RE 81 sunilist 4 cese tod svo pERM Id RICE T ELLAS 81 sumnodes M s cn Se ERE ys dened doe den 81 System li rocii siie erae ce rerv e e ida 64 T UbrOW EE 30 U higeet ate teed 20 UTEN Wa es ove bee Ce Ert See he Pee eee 64 upd te array 3 croceo tnd eeu vee eed 71 V variable in term 2 in vicduvr ces tl bade dacs 97 write depth 2 cess dk eH bh sare ds 52 Y Wap Mag Qos casi dekade 73 23 3 Compatibility with the ISO Prolog standard The Prolog standard was developed by ISO IEC JTC1 SC22 WG17 the international standardization working group for the programming language Prolog The book Prolog The Standard by Deransart Ed Dbali and Cervoni gives a complete description of this standard Development in YAP from YAP4 1 6 onwards have striven at making YAP com patible with ISO Prolog As such Chapter 23 Compatibility with Other Prolog systems 205 YAP now supports all of the built ins required by the ISO standard and 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 By default YAP uses immediate update semantics for its database and not logical update semantics as per the standard see Section 23 2 SICStus Prol
145. earch binary trees They are named after their inventors Adelson Velskii and Landis and they were the first dynamically balanced trees to be pro posed The YAP AVL tree manipulation predicates library uses code originally written by Martin van Emdem and published in the Logic Programming Newsletter Autumn 1981 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 element 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 84 YAP
146. ed that is associated with an atom that will be used to find the array Anonymous arrays do not have a name and they are only of interest if the TERM EXTENSIONS compilation flag is enabled In this case the unification and parser are extended to replace occurrences of Prolog terms of the form X I by run time calls to array element 3 so that one can use array references instead of extra calls to arg 3 s an example g Y Z I J X I is Y J Z I should give the same results as G X Y Z 1 J array element X I E1 array element Y J E2 array element Z I E3 E1 is E2 E3 Note that the only limitation on array size are the stack size for dynamic arrays and the heap size for static not memory mapped arrays Memory mapped arrays are limited by available space in the file system and in the virtual memory space The following predicates manipulate arrays 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 properties Name Size Type Show the prop
147. ed as full prompt on Call Exit Redo and Fail tight prompt on Call Redo and Fail half prompt on Call and Redo loose prompt on Call off never prompt none never prompt same as off The initial leashing mode is full The user may also specify directly the debugger ports where he wants to be prompted If the argument for leash is a number N each of lower four bits of the number is used to control prompting at one the ports of the box model The debugger will prompt according to the following conditions e if N 1 V 0 prompt on fail e if N 2 0 prompt on redo e if N 4 V 0 prompt on exit e if N 8 0 prompt on call 170 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 procedural debugger based in the four port model In this model execution is seen at the procedure level each activation of a procedure is seen
148. eden 97 EE 97 o rm 30 times EE 98 impnamj l l nki tkeeeeBRURIFRR RR Eg evt 96 tOp 8OFb 2 cione de Ver d tac bau AT eps 102 transitive closure 2 s rircrcicriritiersries 102 DES Bees Eens 101 EE 99 iree to list 2 esd EE dd tenner 99 E menn nates gale Posted bed anses 51 Feet eg ER tier AE read deber a e ve es 51 EE 51 EE 51 ttyskip EE 51 ttytab 1 00 eee eee e eee eee eeeeeeees 51 U un hide EE 20 unify with occurs check 2 35 puisse EE 64 u nknownj2s ee ENEE eet 9l unknown predicate handler 3 32 update Array dan saa duer ETE beard e 71 update mutable sores cinriprsrserri srsti 67 se module 11 uge ged irren FR arre 24 use module 2 creber eb ctis mes 25 us 3nodu le 8 ess sere pea edes 25 y variable in term 2 cois crisp nere PNG 97 Vablad2b 2 coe teuren bur rains eb EXPRIME 97 verife attributes 3 110 versn eise rt inq Rt e hier 80 Version T ius este nated ance kjede eR ER ripa 80 vertices 2 eene EROS put Freden EDS 100 vertices edges to ugraph 3 100 196 YAP Prolog User s Manual W Write term Ljrunnk sera dai EREE DETERE ENE P 45 EE EE oy Ee EE e 30 REN ee Ce with output Jo charel 93 write_to_chars 3 np 93 with output to charel 93 KEE 50 with output to chars 4 22 uses svesker 93 working directorae 00 e cece eee eens 96 Y WELLE Da ende 50 write depth 2 AE 52 yap dag 2 scouts tenere dd TDRS DERE SENDES 73 23 1 5 Yap p
149. edicate while choice points for the predicate are available has undefined results asserta_static C Adds clause C to the beginning of a static procedure 56 YAP Prolog User s Manual 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 predicate can be used for dynamic predicates and for static predicates but only if source mode was on when they were compiled clause H B ISO clause whose head matches H is searched for in the program Its head 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 predicate can only be used for dynamic predicates retract C ISO Erases the first clause in the program that matches C This predicate may als
150. ems see see Section 12 21 A Mixed Integer Linear Optimization Example page 133 ordering Spec Provides a means to control one aspect of the presentation of the answer con straints see see Section 12 14 Variable Ordering page 126 12 7 Unification Equality constraints are added to the store implicitly each time variables that have been mentioned in explicit constraints are bound either to another such variable or to a number clp r 2 A 3 B C 2 C 10 0 A B A 1 0 B 1 0 C 10 0 Is equivalent modulo rounding errors to clp r 2 A 3 B C 2 C 10 A B Chapter 12 CLP Q R Manual 119 A 1 0 B 0 9999999999999999 C 10 0 The shortcut bypassing the use of q 1 is allowed and makes sense because the inter pretation of this equality in Prolog and clp R coincides In general equations involving interpreted functors 2 in this case must be fed to the solver explicitly clp r X 3 0 1 0 X 4 0 no Further variables known by clp R may be bound directly to floats only Likewise variables known by clp Q may be bound directly to rational numbers only see see Sec tion 12 12 Numerical Precision and Rationals page 122 Failing to do so is rewarded with an exception clp q 2 A 3 B C 2 C 10 0 A B ERROR not normalized 10 0 This is because 10 0 is not a rational constant To make clp Q happy you have to say clp q 2 A 3 B C 2 C rat 10 1 A B A 1 B 1 C 10
151. en distributed with the Monash University version of clp R Heintze et al 87 and its inclusion into this distribution was kindly permitted by Roland Yap 12 4 Solver Interface Rational numbers are not first class citizens in SICStus Prolog so rational arithmetics has to be emulated Because of the emulation it is too expensive to support arithmetics with automatic coercion between all sorts of numbers like you find it in CommonLisp for example You must choose whether you want to operate in the field of Q Rationals or R Reals use module library clpq Or use module library clpr 12 5 Notational Conventions Throughout this chapter the prompts clp q and clp r are used to differentiate between clp Q and clp R in exemplary interactions In general there are many ways to express the same linear relationship This degree of freedom is manifest in the fact that the printed manual and an actual interaction with the current version of clp Q R may show syntactically different answer constraints despite the fact the same semantic relationship is being expressed There are means to control the presentation see see Section 12 14 Variable Ordering page 126 The approximative nature of floating point numbers may also produce numerical differences between the text in this manual and the actual results of clp R for a given edition of the software 12 6 Solver Predicates The solver interface for both Q and R consist
152. ently 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 Term 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 postprocess the result of the query in several different ways 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 62 YAP Prolog User s Manual findall X a X Y L would be X 32 Y 33 Ls 254 272 no findall T G L L0 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
153. er integers and reals with arithmetic func tions kl one pl terminological reasoning similar to KL ONE or feature trees leq pl standard introductory CHR example handler for less than or equal list pl equality constraints over concatenations of lists or strings listdom pl a straightforward finite enumeration list domains over integers similar to interval pl math elim pl solves linear polynomial equations and inequations using variable elimination several variations possible math fougau pl solves linear polynomial equations and inequations by combining variable elimi nation for equations with Fourier s algorithm for inequations several variations possible math fourier pl a straightforward Fouriers algorithm to solve polynomial inequations over the real or rational numbers 156 YAP Prolog User s Manual math gauss pl a straightforward elegant implementation of variable elimination for equations in one rule minmax pl simple less than and less than or equal ordering constraints together with min imum and maximum constraints modelgenerator pl example of how to use CHR for model generation in theorem proving monkey p1 classical monkey and banana problem illustrates how CHR can be used as a fairly efficient production rule system osf pl constraints over order sorted feature terms according to the OSF theory oztype pl rational trees with d
154. ered Cleanup Calls 97 7 17 Calls With Dmeout ees 98 7 18 Updatable Binary rees 99 7 19 Unweighted Grapnbs eee eee eee eee ee 99 B Extensions 2 99 das enn var ab OR e oe M eii 103 9 Rational Trees gen ox gem A 105 10 Cette EEN x RTT ERES RES 107 11 Attributed Variables 109 11 1 Attribute Declarations lesse esses 109 11 2 Attribute Mammulaton esses 109 11 3 Attributed Unbeaton 0 ele 110 11 4 Displaying Attribut S 0 cece ee eee 111 11 5 Projecting Attributes 0 0 cee eee eere 111 11 6 Attribute sample 111 12 PEP OR Manidalssesreseveusseo taco wes 115 191 Introduction to CLP OB s rvest tern b er perd End ed 115 12 2 Referencing CLP Q R svarene apt y Rene Ra RR 115 12 3 CLP QR Acknowledgments 0 200 eee 115 12 4 Solver Interface 22 etai rd A ae TU Feds 116 12 5 Notational Convention 116 12 6 Solver Dredicates eee eee 116 12 5 JUnilcablon 024 3 suse nd recta aed bei etie reae 118 12 8 Feedback and Bindings leues elei sese 119 12 9 Linearity and Nonlinear Residues 119 12 10 How Nonlinear Residues are made to disappear 120 12 11 Isolation AXIOMS seoanei eto Ree ert ete 121 12 12 Numerical Precision and Rationals 122 12 13 Projection and Redundancy Elimination 125 12 14 Variable Ordering Ad ir Aa eee ee 126 12 15 Turning Answers into Terms s
155. erent 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 e 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 10 YAP Prolog User s Manual 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 simple example is shown next usr local bin yap L Hello World script file using Yap 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 usr bin yap L Hello World script file using Yap 4 initializ
156. ern 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 matching 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 b 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
157. erties 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 name Name to a compound term of name Name This built in will silently fail if the there is no static array with that name 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 s
158. es 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 matching the null string at the beginning of the input string matching the null string at the end of the input string a followed by a single character matching that character or a single character with no other significance matching that character 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 0pts 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 0pts SubMatchVars
159. es in Term is touched Id is unified with an internal object representing the constraint This predicate only gets defined when a handler and constraints are declared see Section 13 3 2 CHR Declarations page 140 find constraint Pattern Id Nondeterministically enumerates constraints from the constraint store that match Pattern i e which are instances of Pattern Id is unified with an internal object representing the constraint find constraint Var Pattern Id Nondeterministically enumerates constraints from the constraint store that de lay on Var and match Pattern i e which are instances of Pattern The identifier Id can be used to refer to the constraint later e g for removal findall constraints Pattern List Unifies List with a list of Constraint if Id pairs from the constraint store that match Pattern findall constraints Var Pattern List Unifies List with a list of Constraint Id pairs from the constraint store that delay on Var and match Pattern remove constraint Id Removes the constraint Id obtained with one of the previous predicates from the constraint store unconstrained Var Succeeds if no CHR constraint delays on Var Defined as unconstrained X find constraint X _ _ fail unconstrained notify constrained Var Leads to the reconsideration of the constraints associated with Var This mech anism allows solvers to communicate reductions on the set of possible values o
160. eysort 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 T he procedure can be used to find the length of a pre defined list or to build a list of length S 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 Chapter 6 Built In Predicates 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 ISO Natural logarithm log10 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 tanh X Hyperbolic tangent asinh X Hyperbolic arc sine acosh X Hyperbolic arc cosine atanh X Hyperbolic arc tangent 37 38 YAP Prolog User s Manual 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 p
161. f variables prior to making bindings 13 3 8 Consulting and Compiling Constraint Handlers The CHR compilation process has been made as transparent as possible The user deals with files containing CHR just as with files containing ordinary Prolog predicates Thus CHR may be consulted compiled with various compilation modes and compiled to file 146 YAP Prolog User s Manual 13 3 9 Compiler generated Predicates Besides predicates for the defined constraints the CHR compiler generates some support predicates in the module containing the handler To avoid naming conflicts the following predicates must not be defined or referred to by user code in the same module verify attributes 3 attribute goal 2 attach increment 2 attach F A 2 for every defined constraint F A F A NM Arity for every defined constraint F A N M is are integers Arity gt A For the prime number example that is attach increment 2 attach prime 1 2 attach primes 1 2 attribute goal 2 goal expansion 3 prime 1 prime 1 1 2 prime 1 1 0 3 prime 1 2 2 primes 1 primes 1 1 2 verify attributes 3 If an author of a handler wants to avoid naming conflicts with the code that uses the handler it is easy to encapsulate the handler The module declaration below puts the handler into module primes which exports only selected predicates the constraints in our example module primes primes 1 prime 1 use module library chr handler eratost
162. f the external representation 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 7A The predicate holds when the first argument is a list of atoms and the second unifies with the atom obtained by concatenating all the atoms in the first list atom length 4 7I 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 41 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 A1 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 me
163. f the term The range of the positive integer is from 0 to but not including Range If Depth is 1 the whole term is considered Otherwise the term is considered only up to depth 1 where the constants and the principal functor have depth 1 and an argument of a term with depth I has depth I 1 term variables Term Variables Unify Variables with a list of all variables in term Term variant Termi Term2 Succeed if Term1 and Term2 are variant terms 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 Terml variable in term Term Var Succeed if the second argument Var is a variable and occurs in term Term 98 YAP Prolog User s Manual 7 16 Call With registered Cleanup Calls 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 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 fragile predicate is used in a query it will be called through call_cleanup 1 fragile foo 1 bar baz 2 call cleanup Goal Exe
164. fferently from SICStus Prolog YAP does not have a notion of interpreted code AII 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 available 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 Chapter 23 Compatibility with Other Prolog systems 197 Prolog flags are different in SICStus Prolog and in YAP The SICStus Prolog on exception 3 and raise exception built ins correspond to the ISO builtins catch 3 and throw 1 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 YAP allows asserting and abolishing static code during execution through the assert static 1 and abolish 1 builtins This is not allowed in Quintus Prolog or SICStus Prolog YAP
165. function in Unix systems when available and the GetComputerName function in WIN32 systems 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 96 YAP Prolog User s Manual pid Id Unify Id with the process identifier for the current process n 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 Execute command Command with its streams connected to InputStream OutputStream 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 working directory CurDir NextDir Fetch the current directory at CurDir If NextDir is bound to an atom make its value the cur
166. han the corresponding simplification rule since the constraints comprising Heads1 will not be removed and inserted again 13 3 4 How CHR work Each CHR constraint is associated with all rules in whose heads it occurs by the CHR compiler Every time a CHR constraint is executed called or woken and reconsidered it checks itself the applicability of its associated CHR by trying each CHR By default the rules are tried in textual order i e in the order they occur in the defining file To try a CHR one of its heads is matched against the constraint Matching succeeds if the constraint is an instance of the head If a CHR has more than one head the constraint store is searched for partner constraints that match the other heads Heads are tried from left to right except that in simpagation rules the heads to be removed are tried before the 142 YAP Prolog User s Manual head constraints to be kept this is done for efficiency reasons If the matching succeeds the guard is executed Otherwise the next rule is tried The guard either succeeds or fails guard succeeds if the execution of its Ask and Tell parts succeeds and in the ask part no variable that occurs also in the heads was touched or the cause of an instantiation error The ask guard will fail otherwise A variable is touched if it is unified with a term including other variables from other constraints different from itself Tell guards on the contrary are trusted and not checke
167. hat if we find X leq Y and another X leq Y in the constraint store we can remove one Finally the rule transitivity states that the conjunction X leq Y Y leq Z implies X leq Z Operationally we add X leq Z as redundant constraint without removing the constraints X leq Y Y leq Z This kind of CHR is called propagation CHR Propagation CHR are useful as the query A leq B C leq A B leg C illustrates The first two constraints cause CHR transitivity to fire and add C 1eq B to the query This new constraint together with B leq C matches the head of CHR antisymmetry X leq Y Y leq X So the two constraints are replaced by B C Since B C makes B and C equivalent CHR Chapter 13 Constraint Handling Rules 139 antisymmetry applies to the constraints A leq B C leq A resulting in A B The query contains no more CHR constraints the simplification stops The constraint handler we built has solved A leq B C leq A B leg C and produced the answer A B B C A leq B C leq A B leq C C leq A A leq B propagates C leq B by transitivity 4 C leq B B leq C simplifies to B C by antisymmetry A leq B C leq A simplifies to A B by antisymmetry since B C A B B C Note that multiple heads of rules are essential in solving these constraints Also note that this handler implements a partial order constraint over any constraint domain this generality is only possible with CHR As another example we can implement the sieve of Eratosthenes to
168. he convex hull What does the trick in operational terms is the implicit elimination of the Lambdas from the program formulation Please note that this program does not limit the number of points or the dimension of the space they are from Please note further that 130 YAP Prolog User s Manual quantifier elimination is a computationally expensive operation and therefore this program is only useful as a benchmark for the projector and not so for the intended purpose 12 17 Why Disequations A beautiful example of disequations at work is due to Colmerauer 90 It addresses the task of tiling a rectangle with squares of all different a priori unknown sizes Here is a translation of the original Prolog III program to clp Q R from file library Cclpqr examples squares filled rectangle A C A gt 1 distinct squares C filled zone 1 4 1 _ C O distinct squares distinct squares B C B gt 0 outof C B distinct squares C outof BP outof B1 C B B Bl note disequation outof C B filled zone VIL VIL CO CO V 20 filled zone VIL L3 BIC C2 V lt 0 placed square B L L1 filled zone L1 L2 C C1 Vb V B filled zone Vb B L2 L3 C1 C2 placed square B H HO H1 L L1 B gt H HO 0 H2 H H1 placed square B H2 L L1 placed square B B VIL XIL X V B placed square B HIL
169. he name of the procedure to be called and the Ai are the arguments The number of arguments 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 builtin 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 ely 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
170. henes constraints primes 1 prime 1 13 3 10 Operator Declarations This table lists the operators as used by the CHR library Chapter 13 Constraint Handling Rules 147 op 1200 xfx 0 op 1190 xfx pragma op 1180 xfx gt lt gt op 1180 fy chr spy op 1180 fy chr nospy op 1150 fx handler op 1150 fx constraints op 1150 fx rules e op 1100 xfx ZEN op 1100 xfx op 1050 xfx amp opt 500 yfx 13 3 11 Exceptions The CHR runtime system reports instantiation and type errors for the predicates find constraint 2 findall constraints 3 insert constraint 2 remove constraint 1 notify constrained 1 The only other CHR specific runtime error is CHR ERROR registering New module Module already hosts lt 01d gt An attempt to load a second handler New into module Module already host ing handler Old was made The following exceptional conditions are detected by the CHR compiler CHR Compiler ERROR syntax rule N lt Term gt If the N th Term in the file being loaded violates the CHR syntax see Sec tion 13 3 3 CHR Syntax page 140 CHR Compiler ERROR too many general heads in lt Name gt Unspecific heads in definitions like C N C lt gt true must not be combined with other heads in rule Name CHR Compiler ERROR bad pragma lt Pragma gt in lt Name gt The pragma lt Pragma gt used in rule
171. her solutions Note also that we normally also need to preserve some information to find out 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 Chapter 21 C Language interface to YAP 181 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 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 n1000 1 YAP Term t ARG1 YAP PRESERVE DATA n100 data n100 data type if YAP_IsVarTerm t I n100 data gt next solution YAP MkIntTerm 0 return continue n100 A if YAP IsIntTerm t YAP IntOfTerm t O YAP IntOfTerm t gt 100 E YAP cut failO else I YAP cut succeed The routine starts by getting the dereference value of the argument The call to YAP_ PRESERVE DATA
172. iar mortgage relation from file library C clpqr examples mg mg P T I B MP i T 1 B MP P 1 1I mg P T I B MP T gt 1 Pi P 1 I MP Ti T 1 mg P1 T1 I B MP sample query yields clp r use module library clpqr examples mg clp r mg P 12 0 01 B Mp 1B 1 1268250301319698 P 12 682503013196973 Mp Without projection of the answer constraints onto the query variables we would observe the following interaction 126 YAP Prolog User s Manual clp r mg P 12 0 01 B Mp B 12 682503013196973 _A 11 682503013196971 P Mp _A 1 01 P _B 2 01 _A 1 01 P 3 0301 _A 2 0301 P 4 060401000000001 _A 3 0604009999999997 P 5 101005010000001 _A 4 10100501 P 6 7 8 9 152015060100001 _A 5 152015060099999 P 213535210701001 A 6 213535210700999 P 285670562808011 _A 7 285670562808009 P 368527 268436091 _A 8 36852726843609 P 10 462212541120453 A 9 46221254112045 P _K 11 566834666531657 _A 10 566834666531655 P The variables _A K are not part of the query they originate from the mortgage program proper Although the latter answer is equivalent to the former in terms of linear algebra most users would prefer the former C _D _E _F _G _H _I _J 12 14 Variable Ordering In general there are many ways to express the same linear relationship between variables clp Q R does not care to distinguish between them but the user
173. icate based This means a module consists of a set of predicates or procedures such that some predicates 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 modu
174. if T is currently 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 Chapter 6 Built In Predicates 33 name yap L will return L 121 97 112 and 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 o
175. ila did gc margin yap flag 2 option gc trace yap flag 2 option Ben ASSOC Bi oir eee ne I edad es EEE EEE Ru D d g et asBS0C 3 cscs eae EN Hand ae ca get ASSOC 5 or tes parade sales IRE PETS get atts 2 rusen eg es Daiena UPS d d get byte l l asd ordiri pIe NEEE P PUR UE SE get byte 2 EE get char l ics eR WV elev bep ie thee ae e e get char 2s cener 4e b E ER heen Fa ede Set 2COde ME get code 2 ei dias Suede ee PENE EREE EiS get from heap 4 iis ve a REPRISE get label 3 o RDIOPRERBAREPPRGGS RET Y get mutable 2 ic eda seder TIENER Ud qu get value 2u he RIVI PEE dade eee vs getO 1 c EE ordeo dedica roD pm getoud 1 uer eae erste a PIDE es getrand 15 ios EE global stack statistics 2 option g oal expansi n 3 2 ve 3t epp feet Yd gro tnd 1 sees rear UT eer AN Grow stack 1 ij eR gw P EREE ET REAT H Malt d OPE h bt 15 2 decm pt cues pue Sand head queue 2 i lg dees Ee dE heap statistics 2 option heap size 2 lg lede deep qam heap to2list Qe ada tne Phe pep RE vere BAGS 1 os ois obesidad es dec estes ina 211 hide predicate 1 sg rete 20 host id 2 c dion bade cs dedi ke dad dd 95 host name 1 12225 0L S meidesteke skins 95 host type yap flag 2 option 75 I a E botas OE E ees 29 include 1 directive i cscirirccisriips nsi 19 INCORE Ledge peren e pE OA TE EEEE SER ud 29
176. imental implementations Chapter 6 Built In Predicates 75 fileerrors gc gc margin gc trace host type index If on fileerrors is on if off default fileerrors is disabled 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 max arity 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 SICStus Prolog sicstus The current default is cprolog This flag affects up
177. in the tree insert T0 Key Value TF Add an element with key Key and Value to the tree TO creating a new AVL tree TF Duplicated elements are not allowed lookup Key Value T Lookup an element with key Key in the AVL tree T returning the value Value new T Create a new tree delete T Key TN Delete element with key Key from the tree T returning a new tree TN 90 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 ex pression 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 eee regular expression is zero or more branches separated by It matches anything that matches one of the branches 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 match
178. index yap_flag 2 option 75 informational_messages yap_flag 2 option DEE 75 initialization O 2g 8 d y p eR 80 initialization 1 directive 21 inse rt 4 2 5 css RM pipueh Ree based 89 ins rt constraint Zassuivisialindashasetess 144 insert constraint 3 2 4 ln 145 instance 2 ices bosdida rA Gedo ddabe ots 59 Inte ger EE 32 integer rounding function yap flag 2 Option ne PERPE P MeeP HERR MC ATEM 75 1972 72 5 v Se debate irte der 39 is Zeg 222230 0 red beboer ARE ees 85 is m table 1 ier creere it Ile ee cae tcr 67 J join queue 3 cosa posda pebDbebeRe dad pg 88 j np queue 3 cose e mh LERRA henaa 88 K key properties 3 soe emere 59 keysort 2 neues Eech eg 36 KIND 5551949494 Pei SD MENU TEE 95 L language yap flag 2 option 75 N T pope tebe gad Cue DV ov ed 85 leash 1 2 o cd ud e dm e Dr Y eve 169 Jength 2 rpa ere RE rye 36 length oueue eini iker aa 88 library directory 1 2 2e rebns 21 22 liStscOBCHbt OD EE 85 List join queue Sisssssyanssnaarsananere ned 88 list 2ump oueue ies here re hiri pid taiag ii 88 list to assoc 2 r d A 83 list to Reap Arbed AER e dE Nd 84 list to ord S6t 22 553 ges eh SRL ehe 86 last to queue 2 iB hoy ows ve rubens 88 list to tee ene EE de EN 99 listing 0 savn dekor heb pr bakre s k Res YS 56 ne deeg ions dansende 56 local stack statistics 2 option T3 look p S cedo rer
179. 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 0 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 0 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 verb eat active type_of_verb rest passive Chapter 21 C Language interface to YAP 175 21 C Language interface to YAP YAP provides the user with the necessary facilities fo
180. ing 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 AccOut Calls the predicate Pred on all sub terms of Term and collect a result in Accu mulator depth first and left to right order 82 YAP Prolog User s Manual Examples hgiven plus X Y 2 Z is X Y plus if pos X Y 2 Y gt 0 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 success maplist plus 1 1 2 3 4 2 3 4 5 checklist var X Y Z selectlist lt 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 717 727 737 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 s 1 2 3 c 1 s 1 2 3 7 2 Association Lists The following association list manipulation predicates are available once included with the use module library assoc command assoc to list Assoc List Given an association list Assoc unify List with a list of the form Key Val where the ele
181. 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 ball is thrown and the handler writes Quota exhausted Execution then continues from the handler Note that in this case 1oop 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 once_with_alarm Time Goal DoOnAlarm catch execute_once_with_alarm Time Goal alarm DoOnAlarm J 66 YAP Prolog User s Manual execute once with alarm Time Goal alarm Time alarm _ call Goal gt alarm 0 alarm _ alarm 0 alarm 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 OldAction Callable Set the interrupt handler for soft interrupt Signal to be Callable OldAction is unified with the previous handler Only a subset of
182. is predicate is used by the grammar rules compiler and is defined as C THT 4 2 6 12 Access to Operating System Functionality The following built in predicates allow access to underlying Operating System function ality cd D Changes the current directory on UNIX environments environ E S This backtrackable predicate unifies the first argument with an environment variable E and the second with its value S It can used to detect all environment variables 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 0 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 pute
183. isequality and OZ type constraint with intersection pathc pl the most simple example of a handler for path consistency two rules primes pl elegant implementations of the sieve of Eratosthenes reminiscent of the chem ical abstract machine model also illustrates use of CHR as a general purpose concurrent constraint language scheduling pl simple classical constraint logic programming scheduling example on building a house tarski pl most of Tarski s axiomatization of geometry as constraint system term pl Prolog term manipulation built in predicates functor 3 arg 3 2 as con straints time pc pl grand generic handler for path consistency over arbitrary constraints load via time pl to get a powerful solver for temporal constraints based on Meiri s unifying framework time rnd pl contains a generator for random test prob lems time point pl quantitative temporal constraints over time points using path consistency tree pl equality and disequality over finite and infinite trees terms type pl equalities and type constraints over finite and infinite trees terms You can consult or compile a constraint handler from the CHR library using e g library C chr examples gcd compile library chr examples gcd If you want to learn more about the handlers look at their documented source code Chapter 13 Constraint Handling Rules 157 In add
184. ist of character codes Result Result0 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 Number Result0 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 Chars0 with output to chars Goal Stream CharsO Chars Execute goal Goal
185. ition there are files with example queries for some handlers their file name starts with examples and the file extension indicates the handler e g bool examples adder bool examples benchmark math examples deussen bool examples diaz bool examples fourier math examples holzbaur math examples limi math examples lim2 math examples lim3 math examples puzzle bool examples queens bool examples queens domain examples stuckey math examples thom math 13 7 Backward Compatibility In this section we discuss backward compatibility with the CHR library of Eclipse Prolog 1 The restriction on at most two heads in a rule has been abandoned rule can have as many heads as you like Note however that searching for partner constraints can be expensive 2 By default rules are compiled in textual order This gives the programmer more control over the constraint handling process In the Eclipse library of CHR the compiler was optimizing the order of rules Therefore when porting a handler rules may have to be reordered good heuristic is to prefer simplification to simpagation and propagation and to prefer rules with single heads to rules with several heads Instead of manually rearranging an old handler one may also use the following combination of options to get the corresponding effect option rule ordering heuristic option revive scheme old 3 For backward compatibility the already in store already in head and guar
186. ken after syntax errors See yap flag 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 char conversion IN 0UT 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 Chapter 6 Built In Predicates 45 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 O0UT ISO If IN is unbound give all current character translations 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 i
187. kept This source is then accessible through the clause 2 procedure and through the listing family of built ins 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 implements a module system compatible with the Quintus Prolog module system The YAP module system is pred
188. 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 EXTRAS 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 eg 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 Chapter 1 Installing YAP 5 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
189. l predicate declared in the module or not use_module F Loads the files specified by F importing 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 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 Other wise 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 call 1 was defined that is it only knows of primitives similar problem arises for assert 1 and friends The meta ca11 1 declaration informs the system that some arguments of a procedure are goals clau
190. lable in YAP Jeg 2794 Nc 2 Nei 2 NE 2 Nf 3 3 Nei 2 NG DH Nd DH ND ND 7i Print a single tilde The next argument must be an atom that will be printed as if by write 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 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 s an example format 8e 8E 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 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 15000 150 00 15000 Identical to Nd except that commas are used to separate groups of three digits format 2D D 150000 150000 1 500 00 150 000 Identical to Nd except that 7 is used to separate groups of three digits format 2D D 150000 150000 1 500 00 150 000 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 ki Print the next argument with write canonical format Good night k a 1 2 Good night a 1 2 7 Mo Print N
191. laration 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 builtins that manipulate attributes so that attribute names are preprocessed depending on the module The user goal expansion 3 mechanism is used for this purpose 110 YAP Prolog User s Manual 11 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 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 builtins are rewritten by the system into internal builtins and that the rewriting process depends on the module on which the builtins have been invoked Module get atts Var ListOfAttributes Unify the list ListOfAttributes with the attributes for the unbound variable Var Each member of the list must be a bound term of the form Attribute Attribute the kbd prefix may be dropped The meaning of and is Attribute Unifies Attribute with a corresponding attribute associated with Var fails otherwise Att
192. ld simply succeed with Goals unified with the empty list 11 4 Displaying Attributes Attributes are usually presented as goals The following routines are used by builtin predicates 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 11 5 Projecting Attributes Constraint solvers must be able to project a set of constraints to a set of variables This is useful when displaying the solution to a goal but may also be used to manipulate computations The user defined project attributes 2 is responsible for implementing this projection Module project attributes QueryVars AttrVars Given a list of variables Query Vars 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 Query Vars 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
193. le declarations exist this is the current type in module The default type in module is user but one can 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 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
194. ler P will be unified with the undefined goal Note that N must be defined prior to calling 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 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 32 YAP Prolog User s Manual user unknown predicate handler G M 7NG 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 goal and the second M set to the current 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
195. les chr spy rules rule 3 transitivity already in store chr spy constraints prime 1 If you set spy points the CHR debugger will be switched on chr nospy Spec Removes spy points on constraints and rules given by Spec where Spec is of the form as described for chr spy Spec There is no chr nospyall 0 To remove all CHR spy points use chr nospy The options available when you arrive at a spy point are described later See Section 13 4 5 CHR Debugging Options page 151 13 4 4 CHR Debugging Messages All trace messages are output to the standard error stream This allows you to trace programs while they are performing file I O The basic format is as follows S 3 1 try eratosthenes absorb 10 prime 9 lt c4 gt prime 10 lt c2 gt S is a spy point indicator It is printed as if there is no spy point as r indicating that there is a spy point on this rule or as c if one of the involved constraints has a spy point The first number indicates the current depth of the execution i e the number of direct ancestors the currently active constraint has The second number indicates the head position of the currently active constraint at rule ports The next item tells you which port is currently traced A constraint or a matching rule are printed next Constraints print as Term Id where Id is a unique identifier pointing into the constraint store Rules are printed as Handler Name 6 followed by
196. lid pointer to a buffer in the code area 21 5 Controlling Yap Streams from C The C Interface 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 second routine that is sometimes useful is void YAP CloseAllO0penStreams 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 180 YAP Prolog User s Manual 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 gi
197. ling of operator declarations in particular during fcompile 1 operator 3 declarations with the same denotation as op 3 but taking effect during com pilation and loading are helpful Example operator 700 xfx operator 600 xfx 13 3 3 Constraint Handling Rules Syntax A constraint handling rule has one or more heads an optional guard a body and an optional name A Head is a Constraint A constraint is a callable Prolog term whose functor is a declared constraint The Guard is a Prolog goal The Body of a rule is a Prolog goal including constraints A rule can be named with a Name which can be any Prolog term including variables from the rule There are three kinds of constraint handling rules Rule Name Simplification Propagation Simpagation pragma Pragma Simplification gt Heads lt gt Guard Body Propagation Heads gt Guard Body Simpagation Heads Heads lt gt Guard Body Chapter 13 Constraint Handling Rules 141 Heads Head Head Heads Head Constraint Constraint it Id Constraint gt a callable term declared as constraint Id gt a unique variable Guard Ask Ask amp Tell Ask gt Goal Tell gt Goal Goal a callable term including conjunction and disjunction etc Body gt Goal Pragma gt a conjunction of terms usually referring to one or more heads identified via 2 The symbol separates th
198. list and index For that task it is more efficient than member 2 nth N List Elem The same as nth0 3 except that it counts from 1 that is nth 1 HI 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 nthO0 2 List c a b d e unifies List with a b c d e nth 4 is the same except that it counts from 1 nth0 4 can be used to insert Elem after the Nth element of Rest 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 List 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 True when List and Reversed are lists with the same elements but in opposite orders 86 YAP Prolog User s Manual same length List1 List2 True when List1 a
199. log User s Manual 95 X0 10 X1 64 X2 76 X3 24 X4 lt 33 43 X0 22 X1 67 X2 68 X3 92 X4 lt 97 39 X0 7 X1 62 X2 54 X3 26 X4 lt 27 48 X0 13 X1 7 X2 61 X3 59 X4 lt 2 49 X0 23 X1 31 X2 76 X3 27xX4 lt 3 50 X0 58 X1 1 X2 57 X3 20 X4 lt 6 13 X0 63 X1 81 X2 3 X3 70 X4 lt 64 20 X0 67 X1 23 X2 41 X3 66 X4 lt 52 81 X0 44 X1 19 X2 22 X3 73 X4 lt 17 43 X0 9 X1 14 X2 27 X3 40 X4 lt 39 16 X0 83 X1 89 X2 25 X3 55 X4 lt 36 2 X0 40 X1 65 X2 59 X3 32 X4 lt 13 65 X0 11 X1 10 X2 13 X3 91 X4 lt 49 93 X0 73 X1 91 X2 1 X3 23 X4 lt 87 7 Consequently the answer consists of the system of nine non redundant inequalities only clp q use module library clpqr examples elimination clp q example 2 X0 X1 X2 X3 X4 X0 2 17 X1 35 68 X2 X3 35 68 X4 25 4 X0 73 93 X1491 93 X2 1 93 X3423 93 X4 29 31 X0 29 25 X1 1 50 X2 57 50 X3 2 5 X4 gt 3 25 X0 7 39 X1 62 39 X2 18 13 X3 2 3 X4 lt 9 13 X0 2 19 X1 64 95 X2 4 5 X3 24 95 X4 gt 33 95 X0 2 3 X1 38 45 X2 53 90 X3 4 15 X4 lt 34 45 X0 23 49 X1 31 49 X2 76 49 X3 27 49 X4 lt 3 49 X0 44 81 X1 19 81 X2 22 81 X3 73 81 X4 gt 17 81 X0 9 43 X1 14 43 X2 27 43 X3 40 43 X4 gt 39 43 The projection the shadow of this polyhedral set into the X0 X1 space can be computed via the implicit elimination of non query variables clp q example 2 XO X1
200. lt c1 gt g Ancestors 1 call primes 10 H lt c1 gt 1 1 try eratosthenes rule 2 0 primes 10 lt c1 gt 1 1 apply eratosthenes rule 2 primes 10 lt c1 gt 1 call prime 10 lt c2 gt 2 insert prime 10 lt c2 gt 2 exit prime 10 lt c2 gt g Ancestors 1 1 apply eratosthenes rule 2 0 primes 10 lt c1 gt 2 call prime 10 c2 amp print constraints prints a list of the constraints in the constraint store With a numeric argument details relevant primarily to CHR implementors are shown n nodebug switches the CHR debugger off debugging outputs information concerning the status of the CHR debugger as via chr debugging O spy this sets a spy point on the current constraint or rule nospy this removes the spy point from the current constraint or rule if it exists show rule prints the current rule instantiated by the matched constraints Ex ample 8 1 apply era absorb 8 0 prime 4 lt c14 gt prime 8 lt c6 gt absorb 8 prime 4 lt c14 gt prime 8 lt c6 gt lt gt 8 mod 4 true lt lt n While in the debugger a printdepth is in effect for limiting the subterm nesting level when printing rules and constraints The limit is initially 10 This com mand without arguments resets the limit to 10 With an argument of n the limit is set to n n argument n of 0 disables depth limit in the debugger a abort calls the built in predicate abort 0 154 YAP Prolog
201. m By default the user output stream is set to a stream correspond ing to the Unix stdout stream version 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 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 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 flag 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
202. m S has stream position end of stream or past end of stream Note that S must be a readable stream set stream position 5 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 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 Chapter 6 Built In Predicates 43 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 stream position P 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 th
203. 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 bound 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 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 non
204. ments Key are in ascending order 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 Chapter 7 Library Predicates 83 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 N Value 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 New Given the binary predicate name Pred and the association list Assoc New in an association list with keys in Assoc and such that if Key Val is in Assoc and Key Ans is in New then Pred Val Ans holds 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 7 3 AVL Trees AVL trees are balanced s
205. mes 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 172 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 same as spy G where G is the active goal nospy this goal stop spying the active goal The same as n
206. nctor 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 YAP Term ts The YAP MkApplTerm function constructs a new term 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 YAP allows one to manipulate the functors of compound term The function YAP_ FunctorDfTerm allows one to obtain a variable of type YAP Functor with the functor to a term The following functions then allow one to construct functors and to obtain their name and arity YAP Functor AP 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 unif
207. nd 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 when append Suffix List holds sum list Numbers Total True when Numbers is a list of integers 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 7 6 Ordered Sets The following ordered set manipulation routines are available once included with the use module library ordsets command n 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 Merge
208. newlines where N defaults to 1 gt NN Print N newlines if at the beginning of the line where N defaults to 1 7 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 1500001 100100100111110000 0x249f0 444760 Note that the letters a z denote digits larger than 9 gt NR 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 0x249F0 444760 The only difference is that letters A Z denote digits larger than 9 dech Print the next argument with print 1 format Good night p a 1 2 Good night a 1 2 reg Print the next argument with writeq 1 7 format Good night q Hello 1 2 Good night Hello 1 2 Nei 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 format The s are 4s woods lovely The woods are love TEMA Print the next argument with writeq 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
209. ng the ISO standard YAP also accepts directives of the form Ox to represent numbers in hexadecimal base and of the form Oo 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 Chapter 3 Syntax 15 10 271010 37101 8712 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 Od 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 float 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 LS where lt dot gt denotes the decimal point character lt exponent marker gt denotes one of e or E 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 rule
210. ntary to Graph In the next example complement 1 3 5 2 4 3 4 1 2 7 5 5 6 7 8 NL 102 YAP Prolog User s Manual NL 1 2 4 6 7 8 2 1 2 5 6 7 8 3 1 2 4 5 8 7 8 4 3 5 6 8 1 5 11 2 3 4 06 7 8 6 1 2 3 4 5 7 8 7 1 2 3 4 5 6 8 8 1 2 3 4 5 6 7 5 compose LeftGraph RightGraph NewGraph Compose the graphs LeftGraph and RightGraph to form NewGraph In the next example c mpose 1 2 2 3 2 4 3 1 2 4 L 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 1138 219 139 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 3 1 4 51 5 1 D V 1 3 5 Chapter 8 Extensions 103 8 Extensions 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
211. ntiated 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 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 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 primitives play a similar role for floating point terms YAP Term YAP MkFloatTerm YAP flt double YAP flt YAP FloatOfTerm YAP YAP Term t where f1t is a typedef for the appropriate C floating point type nowadays a d
212. nts This gets you constant folding and in fact the full algebraic power of the solver applied to the avoidance of computations at runtime The mechanism to realize this idea is to use call residue 2 for the expansion of 1 Asserting with Constraints If you use the dynamic data base the clauses you assert might have constraints on the variables occurring in the clause This should work as follows clp r A lt 10 assert p A A 10 0 yes elpir p X X lt 10 0 YAP currently does not implement this feature 12 24 CLPQR bugs e The fuzzy comparison of floats is the source for all sorts of weirdness If a result in R surprises you try to run the program in Q before you send me a bug report e The projector for floundered nonlinear relations keeps too many variables Its output is rather unreadable e Disequations are not projected properly e This list is probably incomplete Please send bug reports to christian ai univie ac at 136 YAP Prolog User s Manual 12 25 CLPQR References Colmerauer 90 Colmerauer A An Introduction to Prolog III Communications of the ACM 33 7 69 90 1990 Heintze et al 87 Heintze N Jaffar J Michaylov S Stuckey P Yap R The CLP R Programmers Manual Monash University Clayton Victoria Australia Department of Computer Science 1987 Holzbaur 92 Holzbaur C A High Level Approach to the Realization of CLP Lan guages in Proceedings of the JICSLP92 Post
213. nv 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 Chapter 6 Built In Predicates 65 shell 1 Execute command under current shell Acceptable commands are strings or atoms system 1 Execute command with bin sh Acceptable commands are strings or atoms shell O 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 O 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 i 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
214. o 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 portray clause C Write clause C as if written by listing 0 portray clause 5 C Write clause C on stream S as if written by listing 0 Chapter 6 Built In Predicates 57 current atom 4 Checks whether 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 tru
215. oal 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 switch YAP to use logical update semantics YAP Prolog User s Manual By default YAP fails on undefined predicates To follow default SICStus Prolog use 198 e dynamic 1 is a built in not a directive in YAP e yap flag unknown error e 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 Mere 27 KE T 27 EEG 28 LE 27 lt Me 40 ER Em 35 EE 35 n Nc 40 MMC HEN 40 MIRROR 36 EE 40 gt EE EN 40 EE SE 40 GE MENSES EN 36 NE 36 EENEG 36 ASSUM rren EG d Ee 28 A GE EE 30 absolute file name 41 Add 66083 EE 101 e EE 84 add verti6e8 ds i is belle e iad eb otadane des 100 append 8 eee reb ELE E euie PERS 84 BUG R EES 34 assoc to Tisb 2 e apr bebe bi va wee ies 82 at end of etream 0 42 St end of stream 1 NEEN ere ra 42 DEET 32 abom codes 2 i re nhe eee be bey E strie 93 atom to chars 2 A ee IERI EP de 93 atonmi to chars S Ee n i Reb 93 atomic EE 32 attribute goal eee ee eee 111 B bb delete 2 rese page sede ee Ee 61 Db Get EE 61 bb2put ze err Ted e bra e deg
216. og page 196 This affects assert 1 retract 1 and friends Calling set prolog flag update semantics logical will switch YAP to use logi cal update semantics By default YAP implements the atom chars 2 see Section 6 3 Testing Terms page 32 and number chars 2 see Section 6 3 Testing Terms page 32 built ins as per the original Quintus Prolog definition and not as per the ISO definition 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 By default YAP fails on undefined predicates To follow the ISO Prolog standard use set prolog flag unknown error By 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 Error checking for meta calls under ISO Prolog mode is stricter than by default 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 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 206 YAP Prolog User s Manual Appendix A Summary of Yap Predefined Ope
217. ompatible with Q Prolog uui ken se Rasta age RO ae monte id 191 23 1 4 Yap predicates not available in C Prolog 191 23 1 5 Yap predicates not available in C Prolog 196 23 2 Compatibility with the Quintus and SICStus Prolog systems M n 196 23 2 1 Major Differences between YAP and SICStus Prolog edt deny tet PR D tni a o a RR n se 196 23 2 2 Yap predicates fully compatible with SICStus Prolog sy taf ac Mergen eR a b d hh da 198 23 2 3 Yap predicates not strictly compatible with SICStus POlQE zi esca du eit qp Pp d es EE 202 23 2 4 Yap predicates not available in SICStus Prolog ETT 202 23 3 Compatibility with the ISO Prolog standard 204 Appendix A Summary of Yap Predefined Operators 224 verona dot acoso Scc A ge 207 Predicate elen SES cece evox 209 Concept Index ee 2 oer n 217 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 de veloped 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 commerci
218. on 1 directive 21 ntc EET 89 BITS EE 85 1s amp anutable l reeks rer er ber n 67 J jeim q eue 9 a oso eer dre eb ope ib ede 88 jump queue 3 unc icem ce PRESE ds 88 K key properties 3 l l ene 59 Fl N E 95 L EE EE EE E Ee 85 length queue 2s ege Egger ges D gei 88 library directory 1 seeeeseeeeeese 21 22 List comGat 2 4 erecto Rte RERO A 85 Ii5t Join queue 3 ccc tee dads rit e 88 list jump queue 3 0 cece eee eee eee 88 list tOsaS806 2 AE dee 83 Det heap 2 a ae eR ebay 84 list to ord set 2 Lese ioter C DRPI SS Een 86 list to queue 2 n deeg Zeg ER PIRE Sete d 88 list to dree 2 2 eent ER eg 99 Te EE EE 89 M make directory 2 esse scents pee daa 95 make queue 1 s iecru e e br e e me 88 MAPLASSOC EE 83 Imap iree 8 o ieeerese poe e e RE RE HER 99 Imapatgs 2 EE 81 Maplist EE 81 inapnodes 3 onset EE Ee ori 81 EE 85 memberchk 2 adde ept sh E PENE RERET 85 nl hn EM 86 meta predicate 1 directive 25 min ot heap 3 e rscbte RR PD Pe dane ty 84 Min Of heap S vised rast tes DP pe arent 84 inktemp 9 sessi Eae RR ere EE 95 On EE EE EE 24 module 2 directive 2 00 005 24 module 3 directive 0 02 005 24 multifile 1 directive 26255 een bd 21 194 N Heighborsj vaseri s tere Bee Rep ES 101 peighbours 3 e2ccencep RIS NR ERO iro piia 101 NOW Lars veda sane Me rie tsa ns 89 TE RCNH AN 51 NO SO
219. 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 YapCompileClause Term Clause Compile the Prolog term Clause and assert it as the last clause for the corresponding procedure int YapContinueGoal void Continue execution from the point where it stopped void YapError char error description Generate an YAP System Error with descrip tion given by the string error description void YapExit 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 Term YapGetValue Atom at Return the term value associated with the atom at If no such term exists the function will return the empty list YapFastInit 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 YapFastInit is a simpler version of YapInit Yaplnit char SavedState int HeapSize int StackSize int TrailSize int Num berofWorkers int SchedulerLoop int DelayedReleaseLoad int argc char argv Initialize YAP In the future the arguments as a single C structure 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
220. onstraint store will usually be inefficient Starting from an executable specification the rules can then be refined and adapted to the specifics of the application Efficiency can be improved by weakening the guards to perform simplification as early as needed and by strengthening the guards to do the just right amount of propagation Propagation rules can be expensive because no constraints are removed The more heads a rule has the more expensive it is Rules with several heads are more efficient if the heads of the rule share a variable which is usually the case Then the search for a partner constraint has to consider less candidates In the current implementation constraints are indexed by their functors so that the search is only performed among the constraints containing the shared variable Moreover two rules with identical or sufficiently similar heads can be merged into one rule so that the search for a partner constraint is only performed once instead of twice As guards are tried frequently they should be simple tests not involving side effects Head matching is more efficient than explicitly checking equalities in the ask part of the guard In the tell part of a guard it should be made sure that variables from the head are never touched e g by using nonvar or ground if necessary For efficiency and clarity reasons one should also avoid using constraints in guards Besides conjunctions disjunc tions are allowed in the g
221. 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 80 YAP Prolog User s Manual 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 Full name for the directory where YAP is currently consulting the file 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 Chapter 7 Library Predicates 81 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 u
222. 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 machine YAP Prolog User s Manual You should check the default installation path which is set to PROGRA 1 Yap in the standard Makefile This string will usually be expanded into c Program Files Yap 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 mkdir cyg YAPSRC configure enable coroutining NN 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 cygwin1 d11 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 a First it is a good idea to build Yap as a DLL create a project named yapdll using Fil
223. ospy 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 52 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 52 The debugging information when fast skip quasi leap is used will be lost Chapter 20 Indexing 173 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 compilers 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 The indexation generates instructions that test the value of the first argument and then proceed to a selected clause or group of clauses Note that if the first argument was a free variable
224. ouble 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 YAP Term t The following primitives are available for associating atoms with their names YAP Atom YAP_LookupAtom char s YAP Atom YAP_FullLookupAtom char s char YAP AtomName YAP Atom t 178 YAP Prolog User s Manual 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 YAP 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 compound term consists of a functor and a sequence of terms with length equal to the arity of the fu
225. oved by the rule This removal followed by addition is inefficient and may even cause termination problems lf the pragma is used this situation is detected and the corresponding problems are avoided The pragma applies to all constraints removed by the rule already in head Id Shares the intention of the previous pragma but affects only the constraint indicated via Id Note that one can use more than one pragma per rule passive Id No code will be generated for the specified constraint in the particular head position This means that the constraint will not see the rule it is passive in that rule This changes the behavior of the CHR system because normally a rule can be entered starting from each head constraint Usually this pragma will improve the efficiency of the constraint handler but care has to be taken in order not to lose completeness For example in the handler leq any pair of constraints say A leq B B leq A that matches the head X leq Y Y leq X of the antisymmetry rule will also Chapter 13 Constraint Handling Rules 143 match it when the constraints are exchanged B leq A A leq B Therefore it is enough if a currently active constraint enters this rule in the first head only the second head can be declared to be passive Similarly for the idempotence rule For this rule it is more efficient to declare the first head passive so that the currently active constraint will be removed when the rule fires instead of
226. ow 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 short error message s n allocate n K bytes for local and global stacks h n 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 b BOOT FILE boot code is in Prolog file BOOT FILE The filename must define the predicate Slive 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 diff
227. page 148 144 YAP Prolog User s Manual option check guard bindings on off Per default for guards of type ask the CHR runtime system makes sure that no variables are touched or the cause of an instantiation error These checks may be turned off with this option i e all guards are treated as if they were of the tell variety The option was kept for backward compatibility Tell and ask guards offer better granularity option already in store off on If this option is on the CHR runtime system checks for the presence of an identical constraint upon the insertion into the store If present the attempted insertion has no effect Since checking for duplicates for all constraints costs duplicate removal specific to individual constraints using a few simpagation rules of the following form instead may be a better solution Constraint Constraint lt gt true option already_in_heads off on The intention of simplification and simpagation rules is often to combine the heads into a stronger version of one of them Depending on the strength of the guard the new constraint may be identical to one of the heads removed by the rule This removal followed by addition is inefficient and may even cause termination problems If the option is enabled this situation is detected and the corresponding problems are avoided This option applies to all constraints and is provided mainly for backward compatibility Better grained control can b
228. plied redo Prompt at subsequent exits generated by non deterministic rule bodies fail Prompt when a constraint fails wake Prompt when a constraint from the constraint store is woken and reconsidered because one of its variables has been touched try Prompt just before the guard evaluation of a rule after constraints matching the heads have been found apply Prompt upon the application of a rule after the successful guard evaluation when the rule commits and fires just before evaluating the body insert Prompt when a constraint gets inserted into the constraint store i e after all rules have been tried remove Prompt when a constraint gets removed from the constraint store e g when a simplification rule applies The initial value of the CHR leashing mode is call exit fail wake apply Predefined shortcuts are 150 YAP Prolog User s Manual chr leash none chr leash off To turn leashing off chr leash all To prompt at every port chr leash default Same as chr leash call exit fail wake applyl chr leash call No need to use a list if only a singular port is to be leashed 13 4 3 CHR Spy points For CHR programs of any size it is clearly impractical to creep through the entire program Spy points make it possible to stop the program upon an event of interest Once there one can set further spy points in order to catch the control flow a bit further on or one can start creeping Setting a
229. position of the directory search path of YAP specified by N N must be either of first or last remove from 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 p
230. r 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 table 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 exper
231. r 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 1 YAP Term pid YAP MkIntTerm getpid YAP Term out YAP ARG1 return YAP Unify out pid void init my predicates d YAP UserCPredicate my process id my process id 1 The commands to compile the above file depend on the operating system Under Linux i386 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 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
232. ram In more detail the clause g X array element a 2 X will succeed as long as the programmer has used the builtin 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 backtracking 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 70 YAP Prolog User s Manual e int Prolog integers Size would be the natural size for the machine s architecture 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 nam
233. rators 207 Appendix 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 used 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 0p 700 xfx a b c means a b c The following is the list of the declarations of the predefined operators op 1200 fx 7 op 1200 xfx op 1150 fx block dynamic mode public multifile meta predicate sequential table initialization op 1100 xfy 7
234. ream 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 forms as those for put see 6 11 50 YAP Prolog User s Manual tab N Outputs N spaces to the current output stream nl ISO Outputs a new line to the current output stream 6 6 5 Input Output Predicates applied to Streams read S T ISO Reads term T from the stream S instead of from the cu
235. redicates not available in C Prolog These are C Prolog built ins not available in YAP Los The following Prolog text uses lower case letters NOLC The following Prolog text uses upper case letters only 23 2 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 im plemented 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 Di
236. rent 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 Chapter 6 Built In Predicates 77 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 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
237. rent output stream the character whose code is N The current output stream must be a binary stream Chapter 6 Built In Predicates 49 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 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 converted 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 st
238. rent 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 0 J X C cygwin home 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 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 background until the command completes In Unix environments Yap uses the shell given by the environment variable SHELL with the option c In WIN32 environment YAP will use
239. ribute 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 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 11 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 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 Chapter 11 Attributed Variables 111 of goals to be called after Var is unified with Value If verify attributes 3 fails the unification will fail Notice that the verify attributes 3 may be called even if Var has no at tributes in module Module In this case the routine shou
240. ris et als 50 E EE 58 recorda at 3 EE 58 recordaifnot 83 EEN EES 58 60 recordz at 8 esser rper perte RNC Rs 58 recordzifnot 3 ice uet serne Peers 60 Legexp d hove content ee ure b vrbes rg 90 ege celis recere edieen rep Ee tee dd 90 remove duplicates 2 0 000200 eee 85 romove Pom paih cece eee eee 21 rename Dei 95 reset op Counters 167 resize static array 3 seneste reeks nd 71 Pastore EE EE renn 22 EE 56 Chapter 23 Compatibility with Other Prolog systems 195 retractall L i i sssenteeenfebcbeetER Ree DA 56 reyerse A see Debe PUPA pua Rd darn 85 S same length 2 ces EEN TR PER READ 86 88V8 2 Le eiut irs madura SEE EU P dla 22 save Programs sees vinger SNE m 22 Save dprogram 2 sesb oriki i RB REY tr RE 22 Se Gen 6 ies ste Rs Ne idu ppAPORP EUR Yves 86 selectlist A8 Lern E ax p Renc R raa bra erga 81 Serve queue 9 pierre sr d hee RU RAT EE 88 Set pub UL decido Beet Rau rad eb 42 Sek otmen eeh sement 42 set prolog flap 2 cc cee cece eee eee ee 79 set stream Dosition 0 eee eee eee 42 Seb value 2 i cbe bad wea prea DP RES 59 Si MT 67 Sebrand L z cec teed oreraa ine Di IER 89 She Ol 5 oi 96 Shell siu d n A ee Ee ee ive INS PUR 96 show op counters 0000002000 167 show ope by eroup eene 167 GIE 32 GEES 51 SE EEE 97 Socket agent ben pev beni Ate E ner 53 SOGket A 52 Socket accepbt 2 cui See re eh RET daa 53 Socket accept 3 ass rtr ORDER
241. rocedures can be static or dynamic discontiguous G ISO Declare that the arguments are discontiguous procedures 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 1ibrary 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
242. rrect digits in the decimal expansion roughly doubles with each iteration Therefore the numerator and denominator of the rational approximation have to grow likewise clp q use module library clpqr examples root clp q root 3 R print decimal R 70 1 4142156862 7450980392 1568627450 9803921568 6274509803 9215686274 5098039215 R 577 408 clp q root 4 R print decimal R 70 Chapter 12 CLP Q R Manual 123 1 4142135623 7468991062 6295578890 1349101165 5962211574 4044584905 0192000543 R 665857 470832 clp q root 5 R print decimal R 70 1 4142135623 7309504880 1689623502 5302436149 8192577619 7428498289 4986231958 R 886731088897 627013566048 clp q root 6 R print decimal R 70 1 4142135623 7309504880 1688724209 6980785696 7187537723 4001561013 1331132652 R 1572584048032918633353217 1111984844349868137938112 clp q root T R print decimal R 70 1 4142135623 7309504880 1688724209 6980785696 7187537694 8073176679 7379907324 R 4946041176255201878775086487573351061418968498177 3497379255757941172020851852070562919437964212608 Iterating for 8 steps produces no further change in the first 70 decimal digits of sqrt 2 After 15 steps the approximating rational number has a numerator and a denominator with 12543 digits each and the next step runs out of memory Another irrational number that is easily computed is e The following program imple ments an alternating series for 1 e wher
243. rrent 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 5 N ISO As put byte N but to binary stream S put char 5 4 ISO As put char A but to text stream S put code 5 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 stream read the next byte from that stream and unify its code with C Chapter 6 Built In Predicates 51 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
244. ry Cray Research E Andrew Boyd Rice University APPLICATION airline model COMMENTS no integer variables are binary 134 YAP Prolog User s Manual from file library Cclpqr examples mip example flugpl 0bj Vs Ints Vs Anm1 Anm2 Anm3 Anm4 Anm5 Anm6 Stm1 Stm2 Stm3 Stm4 Stm5 Stm6 UE1 UE2 UE3 UE4 UE5 UE6 Ints Obj allpos Vs 1 Stmi 0 9 5tm2 0 9 5tm4 150 Stm1 150 Stm2 150 Stm3 150 Stm4 150 Stm5 150 Stm6 20 Stmi 20 Stm4 Anmi lt 18 57 lt Stm2 57 lt Stm3 Stm3 lt 75 Stm4 lt 75 Anm4 lt 18 Anm5 lt 18 57 lt Stm6 allpos allpos X Xs 2700 Stm1 2700 8tm2 2700 Stm3 2700 Stm4 2700 8tm5 2700 Stm6 100 Anm1 100 Anm2 100 Anm3 100 Anm4 100 Anm5 100 Anm6 1 UE1 lt 1 UE4 lt 1500 Anm1 1500 Anm2 1500 Anm3 1500 Anm4 1500 Anm5 1500 Anm6 1 UE1 1 UE2 1 UE3 1 UE4 1 UE5 1 UE6 0 0 60 0 9 Stmi 1 Anmi 1 Anm2 1 Stm3 0 0 9 Stm3 1 Anm3 1 Stm4 1 Anm4 1 Stmb 0 0 9 Stm5 1xAnm5 1 Stm6 Stm6 Stm5 Stm4 Stm3 Stm2 Anm6 Anm5 Anm4 Anm3 Anm2 Anmi 30 UE1 30 UE2 30 UE3 30 UE4 30 UES 30 UE6 1 5tm2 0 gt 8000 gt gt gt gt gt 20 5tm2 1 UE2 20xStmb 1 UE5 Stm2 75 Anm3 18 57 lt Stmb Stm6 lt 75 9000 8000 10000 9000 12000 lt 0 lt 0 Anm2 lt 18 57 lt
245. s domain X 5 6 7 1 domain Y 3 4 5 6 domain Z 1 6 7 8 X Y Y X domain X 5 6 domain Z 1 6 7 8 yes domain X 5 6 7 1 domain Y 3 4 5 6 domain Z 1 6 7 8 X Y Y Z X 6 Y 6 Z 6 To demonstrate the use of the Goals argument of verify attributes 3 we give an implementation of freeze 2 We have to name it myfreeze 2 in order to avoid a name clash with the built in predicate of the same name module myfreeze myfreeze 2 use module library atts attribute frozen 1 verify attributes Var Other Goals get atts Var frozen Fa are we involved var Other gt must be attributed then get_atts Other frozen Fb has a pending goal 114 YAP Prolog User s Manual gt put atts O ther frozen Fa Fb rescue conjunction put atts O ther frozen Fa rescue the pending goal D Goals Goals Fa J 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 X 2 bindings The two solvers even work together myfreeze X print bound x X domain X 1 2 3 domain Y 2 10 X Y bound x 2 side effect X 2 bindings
246. s 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 the procedures being used in a specific module list profile 4 get number of calls for each profiled procedure setof D M P D1 current module M profile data M P calls D profile data 4 output so that the most often called predicates will come last write profile data LP list profile Module 4 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 write profile data 68 YAP Prolog User s Manual write profile data D M P R ISLP swap the two calls if you want the most often called predicates first format a w 32 t d 12 t 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 p
247. s string gt string quoted characters string quoted characters gt string quoted characters string quoted characters W escape sequence string quoted characters string quoted characters gt string character string quoted characters escape sequence gt a b p elre f t n v escape sequence gt NV om 772 20 escape sequence gt at most 3 octal digit seq char V 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 16 YAP Prolog User s Manual m 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 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 N 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 NxOCN NO1N fU UNN The first three examples return a list including only character 12 form feed The last example escapes the esc
248. s 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 variables They should be used instead of setarg 3 as they allow the encapsulation of accesses to updatable variables Their implementation can also be more efficient for long deterministic computations 205 8 Chapter 6 Built In Predicates 67 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 predicate
249. s 2 ccesse ce asiwedeeewaserge daa 33 atom CONCAG 2 icln dele eo eme ande 33 abonmcOncab 9 coser hospi enimelti i Rp 33 tom length 2 s4rgeteeterasprieranrrkdeas 33 tom to tharsf2 aserusieememere sets erme 93 atom too chars 3 2 osetia cece ERE Re eed 93 attribute goal 2 2cissecec eese meets 111 av inserb 4 Losers hes ete Ee PER 83 al Token eide Seege d h ER B bb delete 2 esee Here nire Yd 61 Dbzget 2 oed het ane oe ehbd T Pedo ad prd 61 ele EE 61 bb update 3 EE 61 C S ERE ERROR CO 64 call cleanup 1 ceri ERR RR REPE 98 call cleamup 2 e 14s e teni RE EO Ae 98 call_countdata 0 c err Rent 68 call count data 8 ve ege Ne dees ER 68 call zesidue 2 d dg PR ODER End 107 call with args n ea an ek i RE ERE REA 29 callable 1 rg See Ee AS 32 cateh 3 ie debe RUE ERR RE RA Opere ES 30 CI MM 64 char code 2 orriaren ere RR REFER ERR 34 Char conversion 2 sce i peste FER E Eg 44 chiecklist 2 icc uri eda epe RUE bagen 81 checknodes 3 ics seen denn dance pet e PRSETER 81 YAP Prolog User s Manual cleanup all 0 4 se see bcr PEE as RE REDI 98 db TE 41 close statie artay Liss ied sere ness 71 Gemetzel PE epee aad 19 compile 1 directive 202 saves rene nes 19 compile expressions 0 isses esee 20 complement 2 iecore rte RE ERR 101 COMPOSE EE 102 compound be eee ead ae ates era XR ens s 32 conylisU 9s issu de vibeke dere bars RIA des 81 COPY tek Peis s dup ede RuREEUbV PH goede
250. s allows support for tracing all calls retries and backtracks in the system This can help in debugging your application but results in performance loss 4 YAP Prolog User s Manual e enable wam profile yes allows profiling of abstract machine instructions This is useful when developing YAP should not be so useful for normal users e enable condor yes allows using the Condor system that support High Throughput Computing HTC on large collections of distributively owned computing resources e enable tabling local batched allows one of the two forms of tabling This option is still experimental e enable parallelism fenv 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
251. s of the following predicates which are exported from module linear Constraint Constraint is a term accepted by the the grammar below The corresponding constraint is added to the current constraint store and checked for satisfiability If you want to overload 1 with other solvers you can avoid its importation via use_module clpq Constraint gt C l C e conjunction C gt Expr Expr equation Expr Expr equation Expr lt Expr strict inequation Expr gt Expr strict inequation Chapter 12 CLP Q R Manual Expr gt Expr lt Expr Expr gt Expr Expr Expr variable number Expr Expr Expr Expr Expr Expr Expr Expr Expr Expr abs Expr sin Expr cos Expr tan Expr pow Expr Expr exp Expr Expr min Expr Expr max Expr Expr Const 117 nonstrict inequation nonstrict inequation disequation Prolog variable floating point or integer unary plus unary minus addition subtraction multiplication division absolute value trigonometric sine trigonometric cosine trigonometric tangent raise to the power raise to the power minimum of the two arguments maximum of the two arguments symbolic numerical constant Conjunctive constraints C C have been made part of the syntax in order to enable grouped submission of constraints which could be exploited by fu ture versions of this software Symbolic numerical constants are provided for compa
252. s 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 only allow asserting clauses for dynamic predicates This is also as specified in the ISO standard YAP allows asserting clauses for static predicates T he 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 builtin 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 assert_static C Adds clause C to a static procedure Asserting a static clause for a pr
253. s written in standard paren thesized prefix notation write term T 0pts 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 writeq T ISO Writes the term T quoting names to make the result acceptable to the predicate read whenever necessary 46 print T format T YAP Prolog User s Manual 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 L Print formatted output to the current output stream The arguments in list L are output according to the string or atom T control sequence is introduced by a w The following control sequences are avai
254. ses or clauses heads and that these arguments must be expanded to receive the current source module 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 ISO Conjunction of goals and Example pi t GO SEA should be read as p X if q X and r X P Q 180 Disjunction of goals or Example pO q X r X should be read as p X if q X or r X true ISO Succeeds once fail ISO Fails always
255. sions 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 Y ISO Succeeds if terms X and Y are not unifiable unify with occurs check T1 7 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 Z 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 Z a X A 2 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 variable 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 or dering e variables come before numbers numbers come before atoms which in turn come before compound terms ie variables lt numbers lt atoms lt compound terms e variables are roughly ordered by age the oldest varia
256. spy point on a constraint or a rule indicates that you wish to see all control flow through the various ports involved except during skips When control passes through any port with a spy point set on it a message is output and the user is asked to interact Note that the current mode of leashing does not affect spy points user interaction is requested at every port Spy points are set and removed by the following predicates which are declared as prefix operators chr spy Spec Sets spy points on constraints and rules given by Spec which is is of the form variable denoting all constraints and rules or constraints Cs where Cs is one of variable denoting all constraints Cru C denoting a list of constraints C Name denoting all constraints with this functor regardless of arity Name Arity denoting the constraint of that name and arity rules Rs where Rs is one of variable denoting all rules R R denoting a list of rules R Name where Name is the name of a rule in any handler Chapter 13 Constraint Handling Rules 151 already in store The name of a rule implicitly defined by the system when the option already in store is in effect already in heads The name of a rule implicitly defined by the system when the option already in heads or the correspond ing pragmas are in effect Handler Name where Handler is the name of a constraint handler and Name is the name of a rule in that handler Examp
257. ssage will be displayed The argument I must be unifiable with a 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 34 YAP Prolog User s Manual 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 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 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 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 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 th
258. stantiated 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 when 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 M 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 prog
259. states Look at the boot yap and init yap files 188 YAP Prolog User s Manual Chapter 23 Compatibility with Other Prolog systems 189 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 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 YA
260. stem which includes a stepper for debugging Many constraint handlers are provided in the example directory of the library CHR are essentially a committed choice language consisting of guarded rules that rewrite constraints into simpler ones until they are solved CHR define both simplification of and propagation over constraints Simplification replaces constraints by simpler constraints while preserving logical equivalence e g X gt Y Y gt X lt gt fail Propagation adds new con straints which are logically redundant but may cause further simplification e g X gt Y Y gt Z gt X gt Z Repeatedly applying CHR incrementally simplifies and finally solves constraints e g A gt B B gt C C gt A leads to fail 138 YAP Prolog User s Manual With multiple heads and propagation rules CHR provide two features which are essential for non trivial constraint handling The declarative reading of CHR as formulas of first order logic allows one to reason about their correctness On the other hand regarding CHR as a rewrite system on logical formulas allows one to reason about their termination and confluence In case the implementation of CHR disagrees with your expectations based on this chapter drop a line to the current maintainer christian ai univie ac at Christian Holzbaur 13 2 Introductory Examples We define a CHR constraint for less than or equal leq that can handle variable ar guments This handler can be found in the library as
261. 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 builtins charsio open mem read stream String 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 94 YAP Prolog User s Manual These builtins 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 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 Se
262. t initially empty 2 add YAPSRC console yap c to the Source Files 3 add YAPSRCN VONincludeNconfig h and the files in YAPSRC include to the Header Files 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 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 1ib T 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 A 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 h
263. t 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 specific There is a strong analogy between the i d b and the way dynamic predicates are stored In fact the main i d b predicates might be implemented using dynamic predicates recorda X T R asserta idb X T R recordz X T R assertz idb X T R recorded X T R clause idb X T R We can take advantage of this the other way around as it is quite easy to write a simple Prolog interpreter using the i d b asserta G recorda interpreter G assertz G recordz interpreter G retract G recorded interpreter G R erase R call V var V fail call H B recorded interpreter H B call B call G recorded interpreter G In YAP much attention has been given to the implementation of the i d b especially to the problem of accelerating the access to terms kept in a large list under the same key Besides using the key YAP uses an internal lookup function transparent to the user to find only the terms that might unify For instance in a data base containing the terms b b a c d e g b X e h stored under the key k 1 when executing the query recorded k _ c _ R recorded would proceed directly to
264. t bytesl 22 2 gie DEEN strekke OPER ERE 49 Eet byle PENE NE 50 getchar T uirse spele dio dete 49 get char 2 ellen Ae rosero piii ren dE 51 get ode l ose es Ee Sek AECH CO SED RG 49 get ode 2 geet uiteten E EPIO eebRH RES 51 Seb value 2 acc syne vete tree bu re Creer 59 EE 64 goal expansion 3 issssssssessseessA 63 prow heap metes ELE eee aware esas 31 BO bake up leresses ege SE 31 H He hasene 20 hide_ptedicate dai ncc krana tease 20 I initialization 1 directive 21 EE 89 K key Goroperties 59 L libraryodirectory T ENN AEN 21 22 list concab 2 coss eder ERU RRRPULEPRIRSEY ES 85 lo kup 3 deed CA UR ERE ATA 89 M Inapargs d cvcs tet rop kane Gates ade 81 re s eec otc te Umen ies E 81 mapnodes 3 sss 81 N Dew EEN 89 E ODER E RAI 20 NOt T Deere dest oe qa dd stu cee Skate 28 numb r atomj 2 ro EEN ENEE E 34 on signal 3 ck ss danse aion RAPERE RE P OPE ed 66 OUCE EE 30 204 P Path ends oko eR eter 20 21 pek byte lyrtanvidv ERE ee ER AN 49 pek byte 2 vri sarte erbe eneren 51 pek Char Zvonerra tast niega pt denn ee 51 peekccode 1 geet det eder rer 49 peek code 2 i24 ded hU PPP pede web IE 51 Profle data deira rev th acd COS pus 68 profiled 2eeeebdt 2 2 ober nti RR Roe eda 68 public 1 directe 22 put byte 1 Seed sr ke epi REA 48 ELE 50 put chat le norte eia RS Ghee eyes dag IS 49 put chat 24xccpescr e beds daa tales 50 put Ode cum beerner Ee 49 put
265. tTree RightTree Construct and return two trees Left Tree and RightTree where Left Tree con tains all items in Tree less than Key and Right Tree 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 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 builtin 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 Chapter 7 Library Predicates 93 write to chars Term ResultO Result Execute the built in procedure write 1 with argument Term outputting the result to the difference l
266. tatic 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 arrays 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
267. tax 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 Chapter 6 Built In Predicates 39 X N Y ISO Integer bitwise conjunction X V Y Iso Integer bitwise disjunction X pr ISO Integer bitwise exclusive disjunction X Y Integer bitwise left logical shift of X by Y places X Y ISO Integer bitwise right logical shift of X by Y places X ISO Integer bitwise negation ged 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 circumrefence to its diameter e The 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
268. 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 module is defined as soon as some 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 typein 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 freep 2228132 maxi stack space 1531904 bytes 464 in use 1531440 freep global stack 96 in use 616684 max local stack 368 in use 546208 maxi trail stack 196604 bytes 8 in use 196596 freep 0 010 sec for 5 code 2 stack and 1 trail space overflowslg 0 130 sec for 3 garbage collections which collected 421000 bytes 0 000 sec for 0 atom garbage collections which collected 0 bytesp 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
269. the related compilation flag as explained in the Makefile 104 YAP Prolog User s Manual Chapter 9 Rational Trees 105 9 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 By default rational trees are not supported in YAP and these terms can easily lead to infinite computation For example X a X X X will enter an infinite loop The RATIONAL TREES flag improves support for these terms Internal primitives are now aware that these terms can exist and will not enter infinite loops Hence the previous unification will succeed Another example X a X ground X will succeed instead of looping Other affected builtins 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 106 YAP Prolog User s Manual Chapter 10 Coroutining 107 10 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
270. 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 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 SIGHUP Hangup sig hup in YAP Reconsult the initialization files yaprc pro logrc and prolog ini SIGUSR1 and SIGUSR2 User signals sig usrl and sig usr2 in YAP Print a message and halt 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 i
271. the third term spending almost the time as if a X or b X was being searched The lookup function uses the functor of the term and its first three arguments when they exist So recorded k _ e h _ would go directly to the last term while recorded k e would find first the fourth term and then after backtracking the last one This mechanism may be useful to implement a sort of hierarchy where the functors of the terms and eventually the first arguments work as secondary keys Chapter 6 Built In Predicates 61 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 blackboard uses the same underlying mechanism as the internal data base but has several important 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 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 sil
272. then both clauses should be tried In general indexation will not be useful if the first argument is a free variable When activating a predicate a Prolog system needs to store state information This information stored in a structure known as choice point or fail point is necessary when backtracking to other clauses for the predicate The operations of creating and using a choice point are very expensive both in the terms of space used and time spent Creating a choice point is not necessary if there is only a clause for the predicate as there are no clauses to backtrack to With indexation this situation is extended in the example if the first argument was the atom nil then only one clause would really be of interest and it is pointless to create a choice point This feature is even more useful if the first argument is a list without indexation execution would try the first clause creating a choice point The clause would fail the choice point would then be used to restore the previous state of the computation and the second clause would be tried The code generated by the indexation mechanism would behave much more efficiently it would test the first argument and see whether it is a list and then proceed directly to the second clause An important side effect concerns the use of cut In the above example some pro grammers would use a cut in the first clause just to inform the system that the predicate is not backtrackable and forc
273. tibility only see see Section 12 19 Monash Examples page 132 entailed Constraint Succeeds iff the linear Constraint is entailed by the current constraint store This predicate does not change the state of the constraint store clp q A lt 4 entailed A 5 A lt 4 yes clp q A lt 4 entailed A 3 no inf Expr Inf Computes the infimum of the linear expression Expr and unifies it with Inf Failure indicates unboundedness sup Expr Sup Computes the supremum of the linear expression Expr and unifies it with Sup Failure indicates unboundedness clp q 2 X Y lt 16 X 2 Y lt 11 118 YAP Prolog User s Manual X 3 Y lt 15 Z 30 X 50 Y sup Z Sup Sup 310 Z 30 X 50 Y X 1 2 Y lt 8 X 3 Y lt 15 X 2 Y lt 1i1 minimize Expr Computes the infimum of the linear expression Expr and equates it with the expression i e as if defined as minimize Expr inf Expr Expr maximize Expr Computes the supremum of the linear expression Expr and equates it with the expression clp q 2 X Y lt 16 X42 Y lt 11 X 3 Y lt 15 Z 30 X 50 Y maximize Z X 7 Y 2 Z 310 bb_inf Ints Expr Inf Computes the infimum of the linear expression Expr under the additional con straint that all of variables in the list Ints assume integral values at the infimum This allows for the solution of mixed integer linear optimization probl
274. tics yap_flag 2 option 78 use module 1 2 beg ERR ete 24 use MOdUle 2 2 ecw he il ddl e e EH rug 25 use module esee 25 user error yap flag 2 option 78 user input yap flag 2 option 78 user output yap flag 2 option 79 V E lice eee et 32 variable in term 2 esee 97 variable names 1 read term 2 option 44 variables 1 read term 2 option 44 Varddnt 2 0 0225 405 hd Ma palier dos 97 verify attributes 3 sess 110 version yap flag 2 option 79 VerSdon O L9 e r Dea ale died Geek 80 VEESTON 1 22 510 Aes Ga aes bd a NA sees 80 vertices 2 1 eG bg ae bee ee ees 100 vertices_edges_to_ugraph 3 100 W W lt 2 wei Minded bea peda PW ieee dite 97 walltime statistics 2 option T3 when 2 Ph OMe teas ea eee eS 107 with output to chars 2 s s 93 with output to chars 3 sorco SIE cens 93 with output to chars 4 s esses 93 Wworking dir ctory 2 0 D bP REO v 96 WEL CO eee ete d dc aono dus pe 45 WE AGO SD e ge een be ed 50 write depth 2 issyuasrnastarseedeke pene ge 52 write strings yap flag 2 option 79 write term sese hn 45 write term S censendum atm sess 50 Write to chars 2 ijv ev PISSOPUCUDH TP 92 Write to chars 3 l i2 be eee es 93 WEACEG eua ere SR CREER 45 wrlt g 2 soda x ee b A S OPERAI DE 50 Predicate Index Y YAP AllocSpace
275. tilities 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 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 combination of maplist and selectlist creates ListOut by applying the pred icate 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 apply
276. ting System dependent Chapter 7 Library Predicates 95 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 U Il type regular P size 2375 Jg Il 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 builtin 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 the hostid function when available host name Name Unify Name with a name for the current host Yap uses the hostname
277. tioning 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 close S 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 stream This feature is not available in ISO or SICStus languages mode and is deprecated close 5 0 ISO Closes the stream S following options O The only valid options are force true and force false YAP currently ignores these options 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 42 YAP Prolog User s Manual
278. 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 use 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 ye
279. tor of imperative languages and can be used alone or with an else part as follows 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 7 P Vy 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 gt Q Ho r T 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 74i Meta call where Name is t
280. tore HET 22 reverse 25 anda bs skare eaeed bekke dn E skiene 85 S same length 2 iuter pr pta er pner 86 save Drogram l nes 22 saye propra vest keen dev RU ER 22 86e KEENE ERE MR ERE 44 seeing locit een deat dad nasa hd dde box eh 44 EE 44 Seleci 3 EEE bae ner dae 86 Serge dene ENEE 88 set anputy T tt eh E EE ehe P iPhones 42 8eb outpub 1 esie ener e t eren deg s 42 set_stream_position 2 00 005 42 setrand T io bebe h g odd Gane 89 shell 0is nati ense ire te ur eR testes 96 Shell Aere ARTE S 96 simple Line ped iet keen heksa aat PNE 32 Skip ls scoosoe se areri repere EE 49 Skip 2 Sube RE De RIT Ee 51 sleep 15 edes ori tee PIOS E EP ERO Pas 97 sockeb 2 oisi bbreRDicuue EE 53 r5 X 52 Socket accept 2 Loose tane Doo bere fama eee 53 socket accept EE 53 socket bmd 2 uictor e PER eb ERES 53 socket buffering A 000005 54 Soeketleee ft cette near E TR REI 53 socket connect 3 ee rer e rre bentes 53 socket eben Lace xe tepore eee 53 socket select 5 000 0 e cece eee eee 54 BOES ved IT NERIS 36 SPY la dise sued e be NER E E ER Se 169 stream select S o2 cedo keep pede ru E Rum 42 SU lge Eet EE erste tue 101 sublist 2 itch puter edaugre RE einen oe ba AS d 86 s bsumes 2 Lese Passes peer samme 97 berne ETS Ae WEE De SA reader 97 du m 86 SOS scout o RICIe A ser LU U MOSS 86 System EE 97 Syslem 2 a ce ERREUR EE 97 system predicate 2
281. 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 92 YAP Prolog User s Manual splay access Return Key Val Tree NewTree If item Key is in tree Tree return its No value for Val and unify Return with true Otherwise unify Return with null The variable NewTree 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 New 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 Left Tree and RighTree into a single tree New 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 Lef
282. ts a new line to stream user output 52 YAP Prolog User s Manual 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 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 Unifies T and L respectively with the values of the maximum depth of a term and the maximum length of a list that will be used by write 1 or write 2 The default value for both arguments is 0 meaning unlimited depth and length write depth 3 5 yes write a b c d e f g a b c yes 7 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
283. uard but they should be used with care The use of other control built in predicates in the guard is discouraged Negation and if then else in the ask part of a guard can give wrong results since e g failure of the negated goal may be due to touching its variables Chapter 13 Constraint Handling Rules 155 Several handlers can be used simultaneously if they do not share constraints with the same name The implementation will not work correctly if the same constraint is defined in rules of different handlers that have been compiled separately In such a case the handlers must be merged by hand This means that the source code has to be edited so that the rules for the shared constraint are together in one module Changes may be necessary like strengthening guards to avoid divergence or loops in the computation 13 6 Constraint Handlers The CHR library comes with plenty of constraint handlers written in CHR The most recent versions of these are maintained at http www pst informatik uni muenchen de fruehwir chr solver html arc pl classical arc consistency over finite domains pool pl simple Boolean constraints cft pl feature term constraints according to the CFT theory domain pl finite domains over arbitrary ground terms and interval domains over integers and reals but without arithmetic functions gcd pl elegant two liner for the greatest common divisor interval pl straightforward interval domains ov
284. ues esleesss 127 12 16 Projecting Inequalities sese eeeeee lesen 127 12 17 Why Diseouations 0 00 00 cece essen 130 12 18 Syntactic Sugar Cien e mee Rec qb RC ree 131 12 19 Monash sample 132 12 20 Compatibility Notes 132 12 21 A Mixed Integer Linear Optimization Example 133 12 22 Implementation Architecture 134 12 23 Fragments and Bts cece eee eee 135 12 24 CLPOR bugs ss erue dI ete da ober rh eh neers 135 12 25 CLPQR R ferences e sene n nee 135 ii iv YAP Prolog User s Manual 13 Constraint Handling Rules 137 Copyn ehto arna E EE gadget dele prid tun 187 13 1 Introd cti nz 44 22d oor e PER eoe eT Pa ERO 137 13 2 Introductory Examples se esee esie 138 13 9 CHER Library zuo art HET Magee E ei 139 13 3 1 Loading the Litan 139 13 3 2 Declarations is ecce eo Rex dea pete 140 13 3 3 Constraint Handling Rules Syntax 140 13 3 4 How CHR work 141 13 3 0 Prag MAS eben dup ea eA 142 153356 OptlOBS iu ede e feret eb e oe e 143 13 3 7 Built In Predicates sssessseee sess 144 13 3 8 Consulting and Compiling Constraint Handlers Len 145 13 3 9 Compiler generated Predicates 145 13 3 10 Operator Declarations 146 13 9 11 Pxeeptions s aarv raredepake dead rete Rn 147 13 4 Debugging CHR Proeramzs sese esses 148 13 4 1 Control Flow Model 148 13 42 CHR Debugging Predicates 148 13 43 CHR
285. unning your program only stopping when a spy point is reached or when the program terminates Leaping can thus be used to follow the execution at a higher level than exhaustive tracing skip over the entire execution of the constraint That is you will not see anything until control comes back to this constraint at either the exit port or the fail port This includes ports with spy points set they will be masked out during the skip The command can be used with a numeric argument to skip the execution up to and including the ancestor indicated by the argument Example 4 exit prime 8 lt c6 gt g Ancestors 1 1 apply eratosthenes rule 2 primes 10 lt c1 gt 2 1 apply eratosthenes rule 2 primes 9 lt c3 gt 3 1 apply eratosthenes rule 2 primes 8 lt c5 gt 4 call prime 8 lt c6 gt 4 exit prime 8 lt c6 gt s 2 2 exit primes 9 lt c3 gt print ancestors provides you with a list of ancestors to the currently active constraint i e all constraints not yet exited that led to the current constraint in the derivation sequence The format is the same as with trace messages Chapter 13 Constraint Handling Rules 153 Constraints start with call entries in the stack The subsequent application of a rule replaces the call entry in the stack with an apply entry Later the constraint shows again as redo or fail entry Example 0 call primes 10 lt c1 gt 1 1 try eratosthenes rule 2 primes 10
286. valuates the expansion namely some calls to the clp Q R solver followed by the call of the purified query As we learned in see Section 12 8 Feed back and Bindings page 119 the solver may bind variables which produces a goal with interpreted functors in it numbers which leads to another stage of expansion and so on We recommend that you only turn on expansion temporarily while consulting or com piling files needing expansion with expand 0 and noexpand 0 12 19 Monash Examples This collection of examples has been distributed with the Monash University Version of cIp R Heintze et al 87 and its inclusion into this distribution was kindly permitted by Roland Yap In order to execute the examples a small compatibility package has to be loaded first clp r use module library C clpqr monash Then assuming you are using clp R clp r expand library C clpqr examples monash rkf45 noexpand clp r go Point 0 00000 Point 0 50000 Point 1 00000 Point 1 50000 Point 2 00000 Point 2 50000 Point 3 00000 Iteration finished 75000 61969 29417 10556 49076 81440 05440 439 derivative evaluations 12 20 Compatibility Notes oS Q QO OQ Oo 00000 ATT93 81233 95809 93977 79929 57522 The Monash examples have been written for clp R Nevertheless all but rkf45 complete nicely in clp Q With rk 45 clp Q runs out of memory This is an instance of the pro
287. var 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 108 YAP Prolog User s Manual dif X Y call residue dif X Y X f Z Y Z L X Z L Y dif f 2 Y dif Z Y T Y f Z L X dif X f Z dif X f 2 no The system only reports one invocation of dif 2 as having suspended Chapter 11 Attributed Variables 109 11 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 unification algorithm is aware of attributed variables and will call user defined handlers when trying to unify these variables Attributed variables provide an elegant abstraction over which one can extend Prolog systems Their main application so far has been in implementing constraint handlers such as Holzbaur s CLPQR and Fruewirth and Holzbaur s CHR but other applications have been proposed in the literature Th
288. ve conditions for modified versions except that this permission notice may be stated in a translation approved by LMU 13 1 Introduction Experience from real life applications using constraint based programming has shown that typically one is confronted with a heterogeneous mix of different types of constraints To be able to express constraints as they appear in the application and to write and combine constraint systems a special purpose language for writing constraint systems called constraint handling rules CHR was developed CHR have been used to encode a wide range of constraint handlers solvers includ ing new domains such as terminological and temporal reasoning Several CHR libraries exist in declarative languages such as Prolog and LISP worldwide more than 20 projects use CHR You can find more information about CHR at URL http www pst informatik uni muenchen de personen fruehwir chr intro html The high level CHR are an excellent tool for rapid prototyping and implementation of constraint handlers The usual abstract formalism to describe a constraint system i e inference rules rewrite rules sequents formulas expressing axioms and theorems can be written as CHR in a straightforward way Starting from this executable specification the rules can be refined and adapted to the specifics of the application The CHR library includes a compiler which translates CHR programs into Prolog pro grams on the fly and a runtime sy
289. ves 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 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 findall 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 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 ot
290. y the terms a and b returning TRUE if the unification succeeds and FALSE otherwise Chapter 21 C Language interface to YAP 179 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 buffer 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 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 void YAP FreeSpaceFromYap void buf The routine releases a buffer allocated from the code area The system may crash if buf is not a va

Download Pdf Manuals

image

Related Search

Related Contents

RC581-FE Installation User Manual  WT310/WT310HC/WT330 Digital Power Meter User`s Manual  Equipements pour machines d`usinage GRACIS  Stellar Industries 5521 User's Manual  Massive Suspension light 37465/43/10  Wilo-Geniax Systemanleitung Elektrik, Elektronik  KeepOut R3  Manuel d`aide  取扱説明書  KoiAir™ Product Manual  

Copyright © All rights reserved.
Failed to retrieve file