Home
SICStus Prolog User's Manual
Contents
1. 336 342 dynamic 1 object method 337 342 dynamic_methods 1 utility method 344 dynamic_objects 1 utility method 344 G get 1 inlined method 0 000 341 get 1 object method 0c cece 342 H has_attribute 1 object method 342 has_instance 1 object method 342 I instance 1 object method 342 M methods 1 utility method 0 344 421 N new 1 object method 000 339 342 new 2 object method 000 339 342 O object built in object sse 342 object 1 object method 000 342 objects 1 utility method o o ooooo 343 or cast 2 utility method 344 P pltrace port arToW asSs0C oooooccccooccccco oo 22 prolog align comments lag oooooocoooommo 23 prolog electric dot flag oooooococooccocoooo 23 prolog electric newline flag 23 prolog electric underscore flag 23 prolog hungry delete key flag 23 prolog imenu flag sess eese 24 prolog indent mline comments flag 23 prolog indent width esss eee eee 22 prolog info predicate index 24 prolog keywords aeol aeiio iae ia cee cence eee 23 prolog object end to 0 flag 23 prolog old sic
2. sss 140 SP register atom C function 137 SP reinstall signal C function 143 SP restore C function sss 153 SP set interrupt hook C function 150 SP set memalloc hooks C function 152 SP set read hook C function 150 SP set reinit hook C function 150 SP set tty C function 004 147 SP set user stream hook C function 148 SP set user stream post hook C function 148 SP signal C function 0 143 SP stream C type o rp eres 145 SP string from atom C function 136 SP SUCCESS Cumacro 4 ee ied exa 128 SP term ref C type di Rr Ree EDD 127 SP term type C function ss 139 SP unify C function sssssssss 140 SP unregister atom C function 137 SP VARIABLE C macro sess 139 splfr utility cee 133 spmkds QUEYIETty mi 4d ex pn Cie d o RA 156 spmkrs utility cece eee eee 154 spy this debugger command 5 67 Spy lai ng vegeta eee Mee eed eee ee 62 121 spypoint condition 3 sese 63 sqrt 1 square root es gia re da 96 stack shifts statistics 2 option 109 statistics Mirta dis iad dee eee VEM 108 Statistics 2 xw r RR NR EN RYE 108 Stream code 2 s csussklbredur gb ku eget esas 145 stream in
3. 02 ee eee eee 31 not blon feeds creek wee ole teed Aes alee 5 426 ODO Misal RR E pra a pda 327 object hierarchy 00 0 e cece 333 object module rir tree s 345 object dynamic 2 0 e eee 327 336 338 object generic 331 object generic implementation 348 object parameterized lessen 331 object parameterized implementation 348 Object SALI eic ned eee ex H ER RH neq 327 336 object oriented programming ssssssss 327 occurs check 2 2 00 er a eee ee eee 36 205 Operating SY SIEM coc staan de apenas tera Che te 215 operator declaration 0 cece eee eee eee 53 OperatOrS oscgnsebes qute de Rr ra CE 37 124 403 ordered sets tia its E EE D PX PER 207 OUUDULc cie viv iE C ere E dee a erae E tata ks 71 output stream current 0 00 cece iii eee 72 overriding inheritance by 0 00 327 P parallel declaration oooooooccccocccncco o 57 parallelism implicit 0 0 eee ee Al parameterized object 0 0 0 e eee eee eee 331 parameterized object implementation 348 DOSU HMOs pad etg e AER RENE Ware ye HER PHARMA qas 273 predicate ra Ney EE ea eR pF ee REE eel 30 32 predicate declaration 00 cee eee e eee eee 53 predicate SPECIAL yaks hein ys 5 predicate asynchronous e sees eee eee ee 46 predicate cavalier
4. 0 0c eee e ee eee 276 30 3 3 Propositional Constraints ooooooooooooo 276 30 3 4 Combinatorial Constraints 0oooocooococoooo 277 30 3 5 User Defined Constraints leeren 280 30 4 Enumeration Predicates 0 0 0 eee eee ene amo 280 30 5 Statistics Predicates 0 0 ccc eee ne 282 30 6 Answer Constraints 0 c cee eee hh 283 30 7 The Constraint System 0 eee eee eens 283 30 71 Definitions ze td ee 283 30 7 2 Pitfalls of Interval Reasoning 0ooooooomoo 284 30 8 Defining Global Constraints 00 e cece ee eee eee 285 30 8 1 The Global Constraint Programming Interface 285 30 8 2 Reflection Predicates 0 c cece eee eee ee 286 30 8 8 FD Set Operations esses eee eee 287 30 8 4 A Global Constraint Example 4 288 30 9 Defining Primitive Constraints 0 0 cece eee eee 290 30 9 1 PORT CaS it A e Rees 291 30 9 2 Range Expressions 0000 eee 291 30 9 3 Term Expressions sese 292 30 9 4 Monotonicity of Indexicals oooooommooo 293 30 9 5 ED predice inca a a hotte 293 30 9 6 Execution of Propagating Indexicals 296 30 9 7 Execution of Checking Indexicals 296 30 9 8 Goal Expanded Constraints oooooooooo 297 30 10 Example Programs oopus seniai raa diaa eee 298 30 10 1 Send More Money 2
5. 41 3 Introduction oe d dee Bees e ey aac a eo Ue Y TS 41 3 2 Running a Parallel Example 00000 41 3 8 Main Issues of Parallel Execution 00 00 ccc cece cence nee 43 3 3 1 The Muse Model luces 43 2 3 2 Schedule Dent mI MEER REN 43 3 3 3 Cut Side Effects and Suspension oocoooccccooo 44 3 4 Visualization Tools 3 2 ee a EPA 44 QUE T UNS Geo utet pera dal ta obe an ace deoa mate oc d e ur da t 45 34 2 VisandOE 5 A cn dee RR Rae gcn 45 3 4 3 Vim stb i eiae te ace dri e de et dena ER RR SR ok 45 3 5 Programming Considerations eese eee 45 4 The Module System vecina 47 4 1 Basic Concepts isis resta rita to wi dE PER EP LE Rd 4T 4 2 Module Prefixing sesseeeeeeee hn 48 4 3 Defining Modules oooocccccccncoroorno rro 48 4 44 Importation 2 21 eR edo Le eee be 49 4 5 Module Name Expansion 00 cee cee eee eee eee eee 49 4 6 Meta Predicate Declarations ooooooororororaron 50 5 Loading Prosrams 2 EXE SERERE EM ee 51 5 1 Predicates which Load Code 10 0 0 ccc ccc cece lille 52 5 2 Declarations ua be nae n death caa an ds acd CR aca 53 5 21 Multifile Declarations lese 54 5 2 2 Dynamic Declarations lesse eese eese 54 5 2 83 Volatile Declarations 0 0000s cece cece ences 55 5 24 Block DeclarationS o oooooooooooooomoooo 55 5 2 5 Meta Predicate Declarati0DS
6. 96 gt 2 boolean greater sess sess 241 2 arithmetic greater or equal 97 gt 2 boolean greater or equal 241 2 2 right shtft aonsoseli e Abe RENDERE 94 2 boolean existential quantifier 241 2 existential quantifier 119 1 bitwise negation cee ease 94 2 bitwise disjunction 05 94 2 inequality of terms 04 97 Xt 71 not provable ccs eo e en etr eden 99 lt lt 2 arithmetic less thad o 96 J2 boolean less iia ee catchy 241 lt 1 message delegation 0 332 lt 2 message delegation 332 72 left shifts ieri cack pa ob bs exe bh oat 94 A abolisSh d oigoukdad bra LAA Wht ees ea RU 115 abollsh 2i2 62x e 115 abort debugger command 00000 67 APOT s eats peels rae hres 17 125 abs 1 absolute value 0 cece eee eee 95 absolute file name 2 sess essssss 89 acos 1 function ccc ccc ccc cece eee 95 acosh 1 function iat EE E ene 96 acot 1 f nction ocn eH RT tri 95 acot2 2 function 0 a cece eese 95 acoth 1 function reren eiu a cece eee ene 96 La AAA a ev br dre peus 206 add edges 3 ic rra eet Sr Ried iaa is 222 226 add to li ap 4 eie Uere pa eee epe al 199 add vertices 3 sie ete e pe Pda 221 225 agc mar
7. n eee eee EE EE eee 339 32 5 2 Method Additions 00 c cece eee eee 339 32 5 3 Parameter Passing to New ObjectS 340 32 6 Access Driven Programming Daemons 22 000 340 32 Llnstancesd c l ale cay ee a fare eben Skee ge eee Ae laced eA 341 32 8 Built In Objects and Methods 00 cee e ee eens 341 32 8 4 Universal Methods 0 cece eee eee eee ee 341 32 8 2 Inlined Methods 0 cece cee eee ee 341 32 8 8 The Proto Object object ce eee ee eee 342 32 8 4 The built in object utility 0 0 000 343 32 9 Expansion to Prolog Code 2 cece eee eee ee 345 32 9 1 The Inheritance Mechanism 04 345 32 9 2 Object Attributes ssesseeeelse re 345 32 9 8 Object Instances 00 a nh 346 32 9 4 The Object Declaration lesse eese 346 32 9 5 The Method Code lsseesseeeeeesee eee 346 32 9 6 Parameter Transfer 000 cece eee eee eee 348 32 10 Examples 322003 ees Vee ee RI IET EC AR bee RULES 350 32 10 1 Classification of BirdS 00oooocooococoooo 350 32 10 2 Inheritance and Delegatiod 0o oooooooo o 351 32 10 83 Prolog programs seeeeeeee eee ee 354 33 Generalized Horn Clause Language 359 34 Tcl Tk Interfaee vicio P emat d ard i y Dor 361 34 1 Prolog to Telerman Cp REPRE been ed es 361 34 1 1 Command F
8. punctuation char In both standards these are character codes 37 40 41 44 91 93 and 123 125 Le the characters 4O 01417 quote char In both standards these are character codes 34 and 39 i e the characters and underline In both standards this is character code 95 i e the character _ token name natural number unsigned float variable string punctuation char layout text full stop name quoted name word symbol solo char layout text 1 layout text quoted name quoted item quoted item char other than or V 22 escape sequence word small letter alpha symbol symbol char except in the case of a full stop or where the first 2 chars are natural number gt digit base alpha where each alpha must be less than the base treating a b and A B as 10 11 400 char item base unsigned float simple float exp exponent sign variable string string item layout text layout text item comment full stop char SICStus Prolog 0 char item 1 yielding the character code for char char 1 other than A escape sequence digit iin the range 2 36 simple float simple float exp exponent digit digit gt e E gt digit sign digit gt gt underline alpha capital letter a
9. link foreign resource Resource SourceFile Option CFiles ObjectFiles Libraries Builds a linked foreign resource Option can be either dynamic or static as described in the alternative form shown below This predicate is not available in Runtime Systems The work of this predicate is done by a command located in SP_PATH bin This command is configurable as described in the Release Notes It can also be invoked directly from a shell as an alternative to running it from Prolog splfr Resource SourceFile dynamic static c CFiles o ObjectFiles 1 Libraries copt COptions Reads terms from SourceFile applying term expansion and extracting any foreign resource 2 fact with first argument matching the name of Resource and all foreign 2 3 facts Compiles CFiles and the interface code derived from these facts and links the resulting object files with ObjectFiles and Libraries to form the linked foreign resource Resource The option dynamic static specifies that the linked foreign resource is suitable for dynamic static linking The default is dynamic The option copt can be used to pass options to the C compiler load foreign resource Resource Unless a foreign resource with the same name as Resource has been statically linked the linked foreign resource specified by Resource is linked into the Prolog load image In both cases the predicates defined by Resource are installed and any init function i
10. Atomic goals in the body of a method clause may be one of the following goal to call the Prolog predicate goal in the source module m goal to call the Prolog predicate goal in module m goal to send the message goal to the object Self goal to send the message goal to a method that may be defined locally or inherited by the object lt goal to delegate the message goal to a method that may be defined locally or inherited by the object object goal to send the message goal to object object object lt goal to delegate the message goal to object object 330 SICStus Prolog Message sending and delegation will be explained later see Section 32 3 Obj Self page 332 The following is a definition for the object list_object It is constructed from three methods append 3 member 2 and length 2 Note that the calls to append 3 and length 2 are to the local definition whereas the member 2 call is to the predicate imported from the Prolog library module lists list_object use module library lists append 3 member 2 amp append L L amp append XIL1 L2 XIL3 append L1 L2 L3 amp member X L member X L amp length 0 amp length L N length L N1 N is Ni 1 The following object apt_1 could be part of a larger database about free apartments in a real estate agency apt_i 4 super apartment amp street_name York amp street number
11. Chapter 30 Constraint Logic Programming over Finite Domains 271 30 Constraint Logic Programming over Finite Domains 30 1 Introduction The clp FD solver described in this chapter is an instance of the general Constraint Logic Pro gramming scheme introduced in Jaffar amp Michaylov 87 This constraint domain is particularly useful for modeling discrete optimization and verification problems such as scheduling planning packing timetabling etc The treatise Van Hentenryck 89 is an excellent exposition of the the oretical and practical framework behind constraint solving in finite domains and summarizes the work up to 1989 This solver has the following highlights e Two classes of constraints are handled internally primitive constraints and global constraints e The constraints described in this chapter are automatically translated to conjunctions of prim itive and global library constraints e The truth value of a primitive constraint can be reflected into a 0 1 variable reification e New primitive constraints can be added by writing so called indexicals e New global constraints can be written in Prolog by means of a programming interface The rest of this chapter is organized as follows How to load the solver and how to write simple pro grams is explained in Section 30 2 CLPFD Interface page 272 A description of all constraints that the solver provides is contained in Section 30 3 Available Constraints page 27
12. db findall Term TermList db_findall DBref Term TermList Unifies TermList with the list of all terms matching Term from the database DBref which defaults to the default database The list is guaranteed to be free of duplicates except in the cases where the same term has actually been stored more than once db_erase TermRef db_erase DBref TermRef Deletes the term in the database DBref which defaults to the default database that is referenced by TermRef if it is not already deleted 238 SICStus Prolog db_canonical TermRef TermID db canonical DBref TermRef TermID Returns the canonical term identifier for the term in DBref which defaults to the default database that is referenced by TermRef db buffering Old New db_buffering DBref Old New Unifies Old with the current buffering mode of DBref which defaults to the defaults database and sets its buffering mode to New which must be on or off Buffering is initially off When it is on modified pages are not immediately flushed to disk enabling faster execution but with a higher risk of inconsistencies if a crash occurs db close always flushes any modified pages 27 5 An Example Session db open my db update on on R set default db R R db 1411928 yes db store a b yes db store a c yes db fetch X X a b X alc no current_db A B C D A my_db B update
13. gt lt in in_set lt lt gt gt EO M gt lt SICStus Prolog Chapter 31 Constraint Handling Rules 305 31 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 above conditions for modified versions except that this permission notice may be stated in a translation approved by LMU 31 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 so
14. 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 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 31 2 Introductory Examples We define a CHR constraint for less than or equal leq that can handle variable arguments This handler can be found in the library as 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 0 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 0 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
15. o ooooooooommmm 17 LI Emacs Interface exe ett eee netsh cea neath th eae 18 1 11 1 Customizing Emacs eese 18 1 11 2 Basic Configuration 0 0 cece eee eee eee 19 LIL3 USagesoconorser iR E RE Re os Seer Led 19 LIA Mode Lite scence ne rie ri eid ehh ae eae bye d 21 LAV Configuration 5243 A rb roe Rea 22 PANG Pips t te oie ER e Rhe dee p RAD RS 24 1 11 6 1 Font locking eese 24 1 11 6 2 Auto fill mode 0 eee eee eee 24 1 14 0 3 SP COO xi UO Rc tite an rr Rl eth 24 1 11 6 4 Changing Colors eene 25 ii SICStus Prolog 2 The Prolog Language 2 2 o rA 27 2 1 Syntax Terminology and Informal Semantics 27 Dll Dermsucasxus Sted eed Te ers ew BAR LD Mb bes 27 2 1 14 Tbe gers e eR red meee eo 27 A err REC Sree I UE eas 27 DA OMS eile lee ape ein eG hace ea Sod oe 28 2 1 1 4 Variables acts nives E Xr OG Dee bed 28 2 1 1 5 Compound Terms sess ee eee ee 28 2 1 2 PTORTAMS 5 iro ep RARE ERO ER wont gears 30 2 2 Declarative Semantics 0 000 ccc cece cece e 33 2 3 Procedural Semantics ce ccc ce cece ee 34 244 Oecurs Ghee ken ELI ee ee e vL 36 2 5 The Cub Symbol eec e E EDI Des 36 2 0 Operatois cocuegR ebbe RR REPERI DULL RR 37 2 5 Syntax Restrictions dieere so eb edu a d pete ce 40 2 9 COMMENES uenerit inrer n rt Rl ed ne P eee e etel 40 3 Running Prolog in Parallel
16. sess 72 user help 0 cici bere ice elemen Meals Finch at 126 user input prolog flag 0008 107 Predicate Index user input stream alias 005 72 user output prolog flag sess 107 user output stream alias esses 72 V Wa Vesti d onic ge ted O 110 variant 2 d ps a ia 205 verify attributes 3 lisse 194 version muse flag option 0 123 version prolog flag cece eee eee 107 Version Q ati a Unete ba ci DPI ER 126 version l c sd reign iP ARI RECEN EPA 126 Vertices 2 Game rera o TERRE RATER 221 225 vertices edges to ugraph B oooooooooooo 221 vertices edges to wgraph 3 sss 225 A gp v ae sale er EUER 367 volatile 1 declaration 0 00085 55 W Walt 2 ze wr na ra taa itera d dd aod 217 walltime statistics 2 option 109 wgraph_to_ugraph 2 0 0 e cece ne 225 WHET 2 osea Tut esta e eoi dt e e eR eoe ace 119 419 with output to chars 2 isse 370 with output to chars 3 lesse 370 with output to chars 4 csse 370 worker id muse flag option 123 working directory 2 csse 217 write debugger command sss 67 LLCS LT reso sie hs cete in VEN Tarte pic draco 82 wiite 2Li 4 cg PERRA YRELP PRESA Er AE 82 write canonical 1 sssss esses esee 82 write canonical 2 sess sese
17. 0c cece eee ene eee eens 46 predicate dynamic cece eee eee eee eee 54 predicate exported 0 cece cece eee 4T predicate ED era eere a e et 293 predicate ho0k oooocooccococccorcccrcn 54 predicate imported 0 cece eee eee ee eee 4T predicate private 0 cece eee eee 4T predicate publics zz eR RE on ere 4T predicate undefined 02 20 ee 15 106 predicate volatile 0c cece cece eee eee ee 55 priority queues roae aa EE enne 199 private predicate 0 eee eee eee 4T procedural semantics ccc eee e eee eee 34 proced re box iW eee MEER 59 procedure Call 2 reb cir rrr rn 35 procedure definition 0000 eee eee 34 process communication 00000 229 231 profiling i i A Oe ia 367 profiling execution esses 121 PLOT ri pie do a See a eed E 30 SICStus Prolog program states errei i nenad n a na SRi EREITEN EREE 104 programming in logic 0 eee eee eee eee 1 programming access driven 000 340 programming object oriented 327 Prolog flagz sS tones hikes 105 108 DPTO Pes ceoere an diu ebd feb dd 327 prototype function 0 eee eee eee 6 public declaration 00 cece eee eee 56 public predicates cic cece cea eem bee pare es 47 Q A gESE bb an RU te Handed hie 8 QUEUES ii force I esa ore See eed eee
18. 1 4 29 3 2 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 Chapter 29 Constraint Logic Programming over Rationals or Reals 255 A B C Residuates unless C is ground or A 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 X cos Y Residuates unless X or Y is ground X tan Y Residuates unless X or Y is ground 29 4 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 funct
19. 240 SICStus Prolog Chapter 28 Boolean Constraint Solver 241 28 Boolean Constraint Solver The clp B system provided by this library module is an instance of the general Constraint Logic Programming scheme introduced in Jaffar amp Michaylov 87 It is a solver for constraints over the Boolean domain i e the values 0 and 1 This domain is particularly useful for modeling digital circuits and the constraint solver can be used for verification design optimization etc of such circuits To load the solver enter the query use_module library clpb The solver contains predicates for checking the consistency and entailment of a constraint wrt previous constraints and for computing particular solutions to the set of previous constraints The underlying representation of Boolean functions is based on Boolean Decision Diagrams Bryant 86 This representation is very efficient and allows many combinatorial problems to be solved with good performance Boolean expressions are composed from the following operands the constants 0 and 1 FALSE and TRUE logical variables and symbolic constants and from the following connectives P and Q are Boolean expressions X is a logical variable Is is a list of integers or integer ranges and Es is a list of Boolean expressions up True if P is false PxQ True if P and Q are both true P Q True if at least one of P and Q is true P Q True if exactly one of P and Q is true X P True
20. Offset Method NewLocation Sets the stream Stream to the byte offset Offset relative to Method and NewLocation is the new byte offset from the beginning of the file after the operation seen Closes the current input stream sequential sequential Specs Not a built in predicate sequential declaration set_input Stream Sets the current input stream to Stream set_output Stream Sets the current output stream to Stream set_stream_position Stream Position Position is a term representing a new position of Stream which is then set to the new position setof Template Goal Set Set is the set of instances of Template such that Goal is satisfied not just provable simple X X is currently uninstantiated or atomic skip C skip Stream C Skips characters from Stream or from the current input stream until after character C skip_line skip_line Stream Skips characters from Stream or from the current input stream until the next LFD sort List1 List2 The list List1 sorted into order yields List2 source_file File source_file Pred File source_file Pred File The predicate Pred is defined in the file File spy Spec Sets spy points on the predicate s specified by Spec not available in Runtime Sys tems spypoint_condition Goal Port Test Sets conditional spy point on the predicate for Goal not available in Runtime Systems Statistics Outputs various execution statistics
21. SP_malloc sizeof int overall counter int SP malloc sizeof int worker counters int SP malloc muse max workers sizeof int Chapter 10 Programming Tips and Examples 185 void init counters 1 int i muse init lock overall counter lock overall counter 0 for i20 i muse num workers i worker counters i 0 long get_counter c long c 1 if c gt 0 return worker counters c else return overall counter long incr_counter int i muse lock overall counter lock i overall counter muse un lock overall counter lock worker counters muse worker id 21 return i We have defined here an overall_counter and an array of worker_counters There is a lock overall_counter_lock ensuring the atomicity of incrementing the overall_counter The code allocate_counter allocates the counters in shared memory The init_counter procedure initial izes all counters while get_counters retrieves the current value of a counter associated with a worker non negative argument or the value of the overall_counter negative argument The incr_counter procedure increments the counter for the worker as well as the overall counter The following Muse code count p1 makes use of the above C routines to accomplish the task of counting the solutions of some goal foreign_resource count allocate counters init counters incr counter get counter foreign
22. The feasibility of integrating the indexical approach with a Prolog based on the WAM was clearly demonstrated by Diaz s clp FD implementation Diaz amp Codognet 93 one of the fastest finite domains solvers around 30 2 1 Posting Constraints A constraint is called as any other Prolog predicate When called the constraint is posted to the store For example X in 1 5 Y in 2 8 X Y T gt Tus Y in 2 3 e 0 0 37 X in 1 5 T in 3 13 XY T X in 1 5 T in 3 13 Y in 2 12 yes Note that the answer constraint shows the domains of nonground query variables but not any constraints that may be attached to them 30 2 2 A Constraint Satisfaction Problem Constraint satisfaction problems CSPs are a major class of problems for which this solver is ideally suited In a CSP the goal is to pick values from pre defined domains for certain variables so that the given constraints on the variables are all satisfied As a simple CSP example let us consider the Send More Money puzzle In this problem the variables are the letters S E N D M O R and Y Each letter represents a digit between 0 and 9 The problem is to assign a value to each digit such that SEND MORE equals MONEY A program which solves the puzzle is given below The program contains the typical three steps of a clp FD program 1 declare the domains of the variables 2 post the problem constraints 274 SICStus P
23. Xn are the elements of the queue To load the package enter the query use module library queues empty queue Queue Is true if Queue has no elements is_queue 4Queue is true when Queue is a valid queue queue X Queue Is true if Queue has one element and that is X queue head Head Queuel Queue2 Queuel and Queue2 are the same queues except that Queue2 has Head inserted in the front It can be used to enqueue the first element in Queue2 Example queue head Head Nq q s s s s 0 1 2 3 41R R Head 1 Nq q s s s 0 2 3 4 _193 _193 R _193 yes queue head list HeadList Queuel Queue2 Queuel and Queue2 have the same elements except that Queue2 has HeadList inserted in the front queue last Last Queuel Queue2 Queue is like Queuel but have Last as the last element in the queue queue last list LastList Queuel Queue2 Queuel and Queue2 are the same queues except that Queue2 has the list of elements LastList last in the queue Example 212 SICStus Prolog queue_last_list 5 6 q s s 0 1 2 R R NQ NQ q s s s s 0 1 2 5 6 _360 _360 R 5 6 _360 yes list_queue List Queue Queue is the queue representation of the elements in List Example list_queue 1 2 3 4 Q Q q s s s s 0 1 2 3 4 _138 _138 yes queue_length Queue Length Length is the number of elements in Queue Example
24. cece RI 298 3010 2 IN QUeOns ta RU EE oe E ee NMES 298 30 10 3 Cumulative Scheduling 0 eee eee eee 300 30 11 Syntax Summary 0 eee ee e 301 Syntax of Indexicals 0 a cee ee eee ene 301 Syntax of Arithmetic Expressions 0 0 0c eee ee eee 303 Operator Declarations 0 000 ccc cece nee teens 304 vil viii SICStus Prolog 31 Constraint Handling Rules 305 Copyright eere e e Lobia Riedie Robes hed ba eek ey 305 31 1 Introduction 3 3 cr nc20e a ar ps RU POM ees 305 31 2 Introductory Examples 0 0 00 306 291 2 CAR Libtary se sige cuit TR RECEIVE Lee ee e 308 31 3 1 Loading the Library 000 00 eee eee 308 31 3 2 Declarations ereet is daa oon E E a EF rna 308 31 3 3 Constraint Handling Rules SyhtaX 309 313 4 How CHR work in be a Rr DERE 310 3133 0 DPragmas se voc ERREUR a IRE A 311 IN iceseessime e eRENDGe3 ed qubd aan da 312 31 3 7 Built In Predicates sceni i ereed eee ee 313 31 3 8 Consulting and Compiling Constraint Handlers 314 31 3 9 Compiler generated Predicates 0oo o ooo 314 31 3 10 Operator Declarations o oooooooooo 315 31 38 11 Exceptions iesirea eee eee ee ces 315 31 4 Debugging CHR Programs 0 eee cece e 316 31 4 1 Control Flow Model 0 cee eee ee ee eee 317 31 4 2 CHR Debugging Predicates ooocoooommmmo 317 31 4 5 CHR Spy
25. dom X wake up when the domain of X has changed min X wake up when the lower bound of X has changed max X wake up when the upper bound of X has changed minmax X wake up when the lower or upper of X has changed val X wake up when X has become ground For an example of usage see Section 30 8 4 A Global Constraint Example page 288 30 8 2 Reflection Predicates The constraint solving method needs access to information about the current domains of variables This is provided by the following predicates which are all constant time operations fd min X Min where X is a domain variable or an integer Min is unified with the smallest value in the current domain of X i e an integer or the atom inf denoting minus infinity fd max X Max where X is a domain variable or an integer Max is unified with the upper bound of the current domain of X i e an integer or the atom sup denoting infinity fd size X Size where X is a domain variable or an integer Size is unified with the size of the current domain of X if the domain is finite or the atom sup otherwise fd set X Set where X is a domain variable or an integer Set is unified with an FD set term denoting the internal representation of the current domain of X see below fd dom X Range where X is a domain variable or an integer Range is unified with a ConstantRange see Syntax of Indexicals page 301 denoting the the current domain of X
26. o o ooooooooo 56 5 2 6 Module Declarations llli eel 56 5 2 7 Public Declarations esee RR 56 5 2 8 Mode Declarations lessen 56 5 2 9 Parallel and Sequential Declarations 57 5 3 Considerations for File To File Compilation 58 6 Debuta er ra e Crete nce LE ES e Sea 59 6 1 The Procedure Box Control Flow Model 59 6 2 Basic Debugging Predicates 00 0 eee 61 6 3 Spy pointss icc di aa ae ele dea dee 62 6 4 Format of Debugging messages 0 0 0 0 e eee eee 63 6 5 Options Available during Debugging 004 65 6 6 Consulting during Debugging 0 eee eee eee 68 6 7 Catching Exceptions 0 0 0 0 cece eee hh 69 7 Built In Predicates 0 0 00 0 e eee 71 dei MEU ye iy A A ee pu e e del st RR SEE 71 7 1 1 Reading in Programs 0 000 73 7 1 2 Term and Goal Expansion 000 eee eeeeee 76 7 1 3 Input and Output of Terms 000 ernus 80 7 1 4 Character Input Output ca ep nn een 8T UL stream lO ss ve Lice A ROREM ine e LS 89 7 1 6 DEC 10 Prolog File 1 O cst ree 93 GT AX Example etre eaaet ane A aes 93 1 2 SAT IUBmUe bl uos ele hale Oe xDD NER xD ue eee 94 7 3 Comparison of Terms 0 00 c cece eee eee hn 97 TAS Control nsum ance ewes bende beth and ee teed aroun be dat A 99 7 5 Error and Exception Handling 0
27. queue_length q s s s s s 0 a b c d e R R L L 5 R _155 yes Chapter 20 Random Number Generator 213 20 Random Number Generator This package provides a random number generator To load the package enter the query use_module library random random Number Binds Number to a random float in the interval 0 0 1 0 Note that 1 0 will never be generated random Lower Upper Number Binds Number to a random integer in the interval Lower Upper if Lower and Upper are integers Otherwise Number is bound to a random float between Lower and Upper Upper will never be generated randseq K N RandomSeq Generates a unordered set of K unique integers chosen randomly in the range 1 N RandomSeg is not returned in any particular order randset k N RandomSet Generates an ordered set of K unique integers chosen randomly in the range 1 N The set is returned in standard order getrand State Tries to unify State with the term rand X Y Z where X Y and Z are integers de scribing the state of the random generator setrand rand X Y Z Sets the state of the random generator X Y and Z must be integers in the ranges 1 30269 1 30307 and 1 30323 respectively 214 SICStus Prolog Chapter 21 Operating System Utilities 215 21 Operating System Utilities This package contains utilities for invoking services from the operating system To load the package enter the quer
28. read Term read Stream Term Reads the term Term from the stream Stream or from the current input stream read_term Term Options read_term Stream Term Options Reads the term Term from the stream Stream or from the current input stream with extra Options reconsult Files Updates the program with interpreted clauses from file s Files recorda Key Term Ref Makes the term Term the first record under key Key with unique identifier Ref recorded Key Term Ref The term Term is currently recorded under key Key with unique identifier Ref recordz Key Term Ref Makes the term Term the last record under key Key with unique identifier Ref reinitialise Initializes Prolog returns to C in recursive calls to Prolog from C repeat Succeeds repeatedly require PredSpecs Tries to locate and load library files that export the specified predicates Creates index files if necessary not available in Runtime Systems restore File Restores the state saved in file File retract Clause Erases repeatedly the next interpreted clause of form Clause retractall Head Erases all clauses whose head matches Head save_program Fle save_program File Goal Saves the current state of the Prolog data base in file File Upon restore Goal is executed see File Makes file File the current input stream 390 SICStus Prolog seeing File The current input stream is named File seek Stream
29. statistics Key Value The execution statistics key Key has value Value Summary of Built In Predicates 391 stream_code Stream StreamCode stream_code Stream StreamCode StreamCode is an integer representing a pointer to the internal representation of Stream Stream interrupt Stream OldHandler NewHandler Sets reads the interrupt handler connected to the stream Stream not available in Muse Stream position 4Stream Position Position is a term representing the current position of Stream stream select Streams TimeOut ReadStreams Returns a list ReadStreams containing streams with pending characters Only the streams in the list Streams are checked TimeOut specifies a timeout on the form off or Sec MicroSec not available in Muse tab N tab Stream N Outputs N spaces to the stream Stream or to the current output stream tel1 File Makes file File the current output stream telling File The current output stream is named File term expansion Terml TermOr Terms term_expansion Term1 Layout1 TermOrTerms Layout2 user term_expansion Term1 TermOrTerms user term_expansion Term1 Layout1 TermOrTerms Layout2 A hook predicate tells expand_term 2 what to do told Closes the current output stream trace Switches on debugging in creep mode not available in Runtime Systems true Succeeds ttyflush Flushes the standard output stream buffer ttyget C The next print
30. 1 4142156862 7450980392 1568627450 9803921568 6274509803 9215686274 5098039215 R 577 408 clp q root 4 R print_decimal R 70 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 7 R print_decimal R 70 Chapter 29 Constraint Logic Programming over Rationals or Reals 257 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 implements an alternating series for 1 e where the absolute value of last term is an upper bound on the error from file library clpqr examples root e N E Err exp 10 N 2 Half 1 2 Y inv_e_series Half Half 3 Err Inv_E E 1 Inv_E
31. 4 super sparking amp faults fault CF1001 Condensation in distributor cap amp fault F1002 Faulty distributor arm amp fault F1003 Worn distributor brushes amp symptoms SICStus Prolog symptom S1001 Starter turns but engine does not fire symptom S1002 Engine has difficulty starting amp symptom S1003 Engine cuts out shortly after starting amp symptom S1004 Engine cuts out at speed amp symptoms contrary to each other contrary 81002 1001 amp contrary 81003 1001 causal effect relationship Chapter 32 Prolog Objects 357 effect F1001 S1001 effect F1002 S1001 effect F1002 S1004 effect F1003 S1002 effect F1003 S1003 F yesno Value write Value nl read yes writeseqnl Prompt L write Prompt write_seq L write seq write seq X L write X write write seq L nl faults faults findall faults Starter turns but engine does not fire yes Location distributor Possible Fault Condensation in distributor cap Engine cuts out at speed yes Location distributor Possible Fault Faulty distributor arm yes faults Starter turns but engine does not fire no Engine has difficulty starting yes Engine cuts out shortly after starting
32. 57 sequential 1 declaration 00 57 Serialized 2 jg es eR ber ERE Y 278 serialized_precedence 3 e cece eee 279 serialized_precedence_resource 4 279 serialized resource 3 000008 279 set printdepth debugger command 68 set subterm debugger command 68 SICStus Prolog set_default_db 1 0 02 eee 237 SSUAINPUL Li e ipe rev 91 Set output ei rrera eser dere teer ote 91 set stream position 2 csse 91 Setof 3 esesctoegi vnde opm oe pRVERI E Dade end 118 Setrand 1 51 dia dida Nr 213 shallow fails profile data A4 option 122 Shetl 0 dre get tise tex a ec cise eee ese 217 SU Lu cett bap uec setup ter tice ER UR 217 Shell 27 ii ele adele deed XR VEMS 217 SHLIB PATH environment sssssse 9 SIMPLE E RR tite EAR 110 sin function dosi ds 95 single var warnings prolog flag 106 sinh 1 function 0 ccc eens 95 skip debugger command 0000 000s 66 A A 88 A M RETIRER 88 sEip Iine 0 b A A Ee 88 skip Ine 1 i bison bcos hives Eesrik Pra as 88 Sleep Al ccs aa thawed sea een thet 217 A oU EIE ERHEBEN 229 SOcket acCept 2 esccesetesediteee ries ERRE EE 229 socket accept 3 ie sse ee e e ere dns 229 Socket bind 2 eae heres RO MIRO ERR 229 s cket close 1 esee esr ere 229 Socket connect 3 dei eese 229 Socket listen 2 4 ibn os le
33. EOF on error int my eof void handle Should return 1 on end of file else 0 void my clrerr void handle Clear the error level int my close void handle Close the stream Should return zero Chapter 8 Mixing C and Prolog 147 8 5 2 2 Installing a New Stream A new stream is made accessible to Prolog with the function SP_make_stream int SP_make_stream void handle int sgetc int sputc int sflush O int seof void sclrerr int sclose O SP stream stream The function will e Allocate a SP stream structure e Install your low level I O functions For those not supplied default functions are installed e Determine if the stream is for input or output or both from the functions supplied e Fill in fields in the SP stream structure with default values The handle pointer will be supplied as the handle argument in the calls to the low level functions A stream without a close function will be treated as not closable i e close 1 will not have any effect on it 8 5 2 3 Internal Representation For most streams you don t have to know anything about the internal representation but there may be occasions when you have to set some fields manually or do some processing on all streams of a particular type SICStus Prolog maintain a circular list of stream objects of type SP stream SP stream backward SP stream forward Used for linking streams together The insertion is done by SP
34. Expr unary minus Expr Expr addition Expr Expr subtraction Expr Expr multiplication Expr Expr division abs Expr absolute value sin Expr trigonometric sine cos Expr trigonometric cosine tan Expr trigonometric tangent pow Expr Expr raise to the power exp Expr Expr raise to the power min Expr Expr minimum of the two arguments max Expr Expr maximum of the two arguments Const symbolic numerical constants Conjunctive constraints C C have been made part of the syntax to control the gran ularity of constraint submission which will be exploited by future versions of this software Symbolic numerical constants are provided for compatibility only see Sec tion 29 7 1 Monash Examples page 266 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 250 SICStus Prolog 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 X42 Y lt 11 X 3xY 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
35. Module ModuleName The Emacs interface will look for the mode line and notify the SICStus Prolog module system that the predicates being incrementally reconsulted or recompiled belong to the module ModuleName If SICStus Prolog recognizes the file as one being loaded before it will remember what module it belongs to If the mode line is missing and the file has not been loaded before the predicates will go into the type in module Even if the file has been loaded earlier its filename may have a slightly different appearance to Prolog via the Emacs interface so it is safest to always include the mode line A mode line can be inserted by choosing Insert Module modeline in the Prolog menu 22 SICStus Prolog 1 11 5 Configuration The behavior of the Emacs interface can be controlled by a set of user configurable settings Some of these can be changed on the fly while some require Emacs to be restarted To set a variable on the fly type M x set variable RET VariableName RET Value RET Note that variable names can be completed by typing a few characters and then pressing TAB To set a variable so that the setting is used every time Emacs is started add lines of the following format to emacs setq VariableName Value The available settings are prolog system The Prolog system to use Available settings are mercury sicstus and swi Defaults to sicstus prolog system version The version of SICStus that is use
36. Mon Mar 2 19 22 44 MET 1998 var tmp aaaa004Cd c generated 20 msec yes Note that we do not specify any Java files to splfr as we would specify C files when building foreign resources for C code This is because the C code can be compiled into the resource itself while the Java code must be loaded at runtime into the JVM This means that the resource will only contain the glue code for calling the JVM and no actual Java code Hence these resources are usually quite small Note also that the use of dynamic is implicit and obligatory resources with Java calls must be dynamic Now we need some Java code to call Simple java public class Simple static int simpleMethod int value return value 42 Chapter 9 Mixing Java and Prolog 173 This Java code must now be compiled Refer to the documentation of your Java implementation exactly how to do this On Solaris this might look like javac Simple java Now we are ready to call the method simple 2 from inside SICStus sicstus SICStus 3 7 Mon Mar 2 19 22 44 MET 1998 compile simple compiling E42 compiled simple pl in module simple 160 msec 48640 bytes yes simple 17 X X 714 yes What has happened is that the predicate simple 2 has been installed as a predicate defined in Java this is not exactly true the predicate is defined as a C function which calls the Java method When we load the simple module we will fir
37. N ISO Character code N is output onto Stream N may be an arithmetic expression These predicates are called put code 1 2 in the ISO Prolog standard tab N tab Stream N N spaces are output onto Stream N may be an arithmetic expression The above predicates are the ones which are the most commonly used as they can refer to any streams The predicates which follow always refer to the standard input and output streams They are provided for compatibility DEC 10 character I O and are actually redundant and easily recoded in terms of the above predicates ttynl Same as nl user ttyflush Same as flush_output user ttygetO N Same as getO user N ttyget N Same as get user N ttyput N Same as put user N ttyskip N Same as skip user N ttytab N Same as tab user N Chapter 7 Built In Predicates 89 7 1 5 Stream I O The following predicates manipulate streams Character and line counts are maintained per stream All streams connected to the terminal however share the same set of counts For example writing to user_output will advance the counts for user_input if both are connected to the terminal Bidirectional streams use the same counters for input and output open FileName Mode Stream ISO open FileName Mode Stream Options ISO If FileName is a valid file name the file is opened in mode Mode invoking the UNIX function fopen and the resulting stream is unified with Stream
38. Sterling amp Shapiro 86 However for the benefit of those who do not have access to a copy of this book and for those who have some prior knowledge of logic programming a summary of the language is included For a more general introduction to the field of Logic Programming see Kowalski 79 See Chapter 2 Prolog Intro page 27 This manual describes a Prolog system developed at the Swedish Institute of Computer Science Parts of the system were developed by the project Industrialization of SICStus Prolog in col laboration with Ericsson Telecom AB NobelTech Systems AB Infologics AB and Televerket The system consists of a WAM emulator written in C a library and runtime system written in C and Prolog and an interpreter and a compiler written in Prolog The Prolog engine is a Warren Ab stract Machine WAM emulator Warren 83 Two modes of compilation are available in core i e incremental and file to file When compiled a predicate will run about 8 times faster and use memory more economically Implementation details can be found in Carlsson 90 and in several technical reports available from SICS SICStus Prolog follows the mainstream Prolog tradition in terms of syntax and built in predicates and is largely compatible with DECsystem 10 Prolog and Quintus Prolog SICStus Prolog Acknowledgments 3 Acknowledgments The following people have contributed to the development of SICStus Prolog Jonas Almgren Johan Andersson
39. The built in predicates read 1 2 normaly raise an exception on syntax errors see Sec tion 7 5 Exception page 101 The behavior is controlled by the flag syntax_errors see prolog_ flag 3 1 6 Undefined Predicates There is a difference between predicates that have no definition and predicates that have no clauses The latter case is meaningful e g for dynamic predicates see Section 5 2 Declarations page 53 that clauses are being added to or removed from There are good reasons for treating calls to undefined predicates as errors as such calls easily arise from typing errors The system can optionally catch calls to predicates that have no definition First the user defined predicate user unknown_predicate_handler 3 see Section 7 5 Exception page 101 is called If undefined or if the call fails the action is governed by the state of the unknown 2 flag which can be trace which causes calls to undefined predicates to be reported and the debugger to be entered at the earliest opportunity error which causes calls to such predicates to raise an exception the default state See Section 7 5 Exception page 101 fail which causes calls to such predicates to fail Calls to predicates that have no clauses are not caught The built in predicate unknown OldState NewState unifies OldState with the current state and sets the state to NewState The built in predicate debugging 0 prints the value of this state along with i
40. The two example solvers interact via bindings to shared attributed variables only More complicated interactions are likely to be found in more sophisticated solvers The corresponding verify_ attributes 3 predicates would typically refer to the attributes from other known solvers modules via the module prefix in Module get atts 2 Chapter 15 Heap Operations 199 15 Heap Operations A binary heap is a tree with keys and associated values that satisfies the heap codition the key of every node is greater than or equal to the key of its parent if it has one The main application of binary heaps are priority queues To load the package enter the query use_module library heaps add_to_heap OldHeap Key Datum NewHeap Inserts the new Key Datum pair into the current heap OldHeap producing the new heap NewHeap 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 Example add_to_heap t 0 t 3 678 N N t 1 1 t 3 678 t t yes get_from_heap OldHeap Key Datum NewHeap Returns the Key Datum pair in OldHeap with the smallest Key and also a NewHeap which is the OldHeap with that pair deleted Example get_from_heap t 1 t 1 543 t t K D N D 543 K 1 N t 0 1 t yes empty heap Heap is true when Heap is the
41. Value Value is the current value of the Muse flag FlagName muse_flag FlagName OldValue New Value OldValue and NewValue are the old and new values of the Muse flag FlagName muse flags Display all Muse flag settings muse sync Synchronize for being leftmost in Muse muse trace Goal muse trace Goal FilePrefix Generate a Muse trace file for Goal name 4 Const CharList name Const CharList The name of atom or number Const is the string CharList nl n Stream Outputs a new line on stream Stream or on the current output stream nodebug Switches off debugging not available in Runtime Systems Summary of Built In Predicates 387 nofileerrors Disables reporting of file errors nogc Disables garbage collection of the global stack nonvar X X is a non variable nospy Spec Removes spy points from the predicate s specified by Spec not available in Runtime Systems nospyall Removes all spy points not available in Runtime Systems notrace nozip Switches off debugging not available in Runtime Systems number X X is currently instantiated to a number number_chars Number CharList number_chars Number CharList The name of the number Number is the list of characters CharList numbervars Term N M Number the variables in the term Term from N to M 1 on_exception Pattern ProtectedGoal Handler Executes the procedure call ProtectedGoal If during the execution ra
42. WOEKGI idler end A ed pte a Rohe 43 428 SICStus Prolog Table of Contents Int rOdHctlon acoso AAA AA EN A 1 Acknowledgments eessseeeee een 3 Notational Conventions eese sese esses 5 Keyboard Characters 0 eee cece cece hh 5 Mode Specie died XR ib eerie hae PRU MER eae eee ei 5 Predicate Pesar es brote REED VER MP emu ES 5 Development and Runtime Systems 2 0 00 cece eee ses 6 Function Prototypes cs case roren net Ure cet Ea Pies OPE eH ers 6 ISO Compliance vc hice tea eda a hee aed eee buen 6 1 How to Run Prolog RE RR ates eee es 7 13 Getting Started connec dd ee da eee BEI BER 7 1 1 4 Finding Libraries at Runtime 004 9 1 1 2 Environment Variables 0 cece eee eee eee 10 1 2 Reading in Programs nicsen ses niedo nipa E nK pA EEE eee 11 1 8 Inserting Clauses at the Terminal 0 00 eee eee 12 1 4 Directives Queries and Commands 00 cess eee 12 1 4 1 Queries vum ey RR RRERE ead eee eee 12 1 4 2 Commands in Rene t de Ra ERAT URB 13 1 5 Syntax BEIIOIS 4e Ee Re AR V RR rie e ate 14 1 6 Undefined Predicates 0 0 0 cece cece eee eee eee 15 1 7 Program Execution And Interruption 2 02 2 eee 15 1 8 Exiting From The Top Level 0 00 0 eee eee eee 16 1 9 Nested Executions Break and Abort 0c eee eee eee 16 1 10 Saving and Restoring Program States
43. address The value passed will be void pointer Prolog address TypeName Chapter 8 Mixing C and Prolog 131 C TypeName The argument should be an integer which value is constrained according to see Sec tion 8 3 2 Creating Prolog Terms page 137 SP_put_address The value passed will be a TypeName pointer Prolog term C SP_term_ref The argument could be any term The value passed will be the internal representation of the term Prolog integer C long The C function is passed a reference to an uninitialized long The value returned will be converted to a Prolog integer Prolog float C double The C function is passed a reference to an uninitialized double The value returned will be converted to a Prolog float Prolog atom C unsigned long The C function is passed a reference to an uninitialized unsigned long The value returned should be the canonical representation of a Prolog atom Prolog chars C char The C function is passed the address of an uninitialized char The returned string will be converted to a Prolog list of character codes Prolog string C char The C function is passed the address of an uninitialized char The returned string will be converted to a Prolog atom Prolog will copy the string to a safe place so the memory occupied by the returned string may be reused during subsequent calls to foreign code Prolog string N C char The C f
44. debugger command s s 66 QUE Listes LIRE ELIO E RU Pd ven costa ws oe ERES 233 P parallel O declaration s esses 57 parallel 1 declaration s sess 57 path 3 serie teeter ern Des DUM 222 226 peek char lz 65b ca EUR 88 peek char 2 vine ar des 88 permission_error 5 error class 103 perm tation 2 uri 203 phrase 2 2 A VERE Bevan ake aes 80 phras 3 ip diede diee plus 80 prd pat deu eoe be aditu emo M Me iuis 216 popen gxcxecurees A t teen CAE ent 217 PU ii yr ck paste pase MD 82 portray diari ei terea eir 269 portray clause 1 dl ete eildt bbb bee 83 portray_clause 2 6c cece 83 portray message 2 sene 102 415 predicate property 2 isses 104 prefix 2 2 vete RM e de pu UL ats dtd 203 prepare foreign resource 3 s sess 374 prepare resource table 2 sss 373 print debugger command sss 66 PEE diaria gea bisous ibique Patna da 82 PEE Li take tra edi a co Re uie edo 82 print messag 2 i ee eee eda ad 102 profile data 4 citada eae oe 122 profile Test Lira vui els 122 program statistics 2 option 109 project_attributes 2 0 eee eee eae 195 prolog flag 2 2e verbe s ty Eb a 108 prolog flagA3 rs or ers er det 105 prolog load context 2 csse se 108 PROLOGINCSIZE environment sss 10 PROLOGINITSIZE environment s 10 PROLOGKEE
45. items linked by the standard Prolog conjunction operator Definite clause grammars extend context free grammars in the following ways 1 A non terminal symbol may be any Prolog term other than a variable or number 2 A terminal symbol may be any Prolog term To distinguish terminals from non terminals a sequence of one or more terminal symbols is written within a grammar rule as a Prolog list An empty sequence is written as the empty list 1 If the terminal symbols are character codes such lists can be written as elsewhere as strings An empty sequence is written as the empty list TJ or 3 Extra conditions in the form of Prolog procedure calls may be included in the right hand side of a grammar rule Such procedure calls are written enclosed in brackets 4 The left hand side of a grammar rule consists of a non terminal optionally followed by a sequence of terminals again written as a Prolog list 5 Disjunction if then if then else and not provable may be stated explicitly in the right hand side of a grammar rule using the operators I gt and A as in a Prolog clause 6 The cut symbol may be included in the right hand side of a grammar rule as in a Prolog clause The cut symbol does not need to be enclosed in brackets As an example here is a simple grammar which parses an arithmetic expression made up of digits and operators and computes its valu
46. lt 11 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 expres sion clp q 2 X Y lt 16 X42 Y lt 11 X 3xY 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 constraint that all of variables in the list Ints assume integral values at the infimum This allows for the solution of mixed integer linear optimization problems see Section 29 8 MIP page 268 clp q X gt Y Z Y gt 1 Z gt 1 bb_inf Y Z X Inf Inf 4 Y gt 1 Z gt 1 X Y Z gt 0 Chapter 29 Constraint Logic Programming over Rationals or Reals 251 bb_inf Ints Expr Inf Vertex Eps Computes the infimum of the linear expression Expr under the additional constraint that all of variables in the list Ints assume integral values at the infimum Eps is a positive number between 0 and 0 5 that specifies how close a number X must be to the next integer to be considered integral abs round X X lt Eps The predicate bb_inf 3 uses Eps 0 001 With clp Q Eps 0 makes sense Vertex is a list of the same length as Ints and contains the integral values for Ints such that the infimum is produced when assigned Note that
47. nth 3 sscrtuin d rec MER ee eet qe Era 202 id bM bebe eis 202 nth0 9 ipe ii CEPRPESCRE UC PE ERES 202 NthO 4 oe Peyote ge cee Pe DAP PEUT UU 202 num workers muse flag option 123 number 1 RIS PRIIRPSRRM EE SERRE 110 nu mber chats 2 x ege da 112 number to chars 2 sse 369 Predicate Index Humberto chars 369 numbervars 3 esses eee eee 124 O on exceptlion 3 5 uso etai de tec pas 101 Op 9 auci ua id sedet ba Ed ada nid 37 124 403 open 3 i wybvetpeRe P dieting ENERMAX 89 OPE A it A ee yee Eras ben 89 open chars stream 2 isses 369 open null stream 1 sse 91 ord_add_element 3 0 e cece eee eee eee 207 ord del element 3 0 0c eee eee eee eee 207 E A eni D e meh Ai 207 e a PA Eb mh 207 ord_intersection 2 0 0c eee o 207 ord_intersection 3 0 e cece eee eee 207 ord_intersection 4 0 0 eese 207 ord_list_to_assoc 2 0 cece eee ee 192 ord member 2 sd pere eta np ee 208 ord seted 2 iio pede IE wine a eet 208 ord setproduct 3 ii eek po vas beris 208 ord subset 2 sce ee eto ERR 208 ord s btract 3 o p techie M pene e 208 ord syidiff 3 v exeun erre yates wee DRE EE ara 208 ord nion 2 cclesvres b dro 209 ord nionZ3 d ars oh earn er eH rer E 208 ord nion 4 Legs WE OUEST QU eT 208 order resource 2 cesse ELE RS 282 Ordering Cinca ira da E Edi 251 260 Otherwise 0 acia ab 100 out
48. otherwise evaluates to inf sup As an optimization R3 is not evaluated while the value of R1 is a non empty set 292 SICStus Prolog unionof X R1 R2 evaluates to the union of S Expr 1 S Expr N where each Expr_I has been formed by substituting K for X in R2 where K is the I th element of S R1 See Section 30 10 2 N Queens page 298 for an example of usage N B If S R1 is infinite the evaluation of the indexical will be abandoned and the indexical will simply suspend switch T1 MapList evaluates to S Expr if S T1 equals Key and MapList contains a pair Key Expr Otherwise evaluates to the empty set When used in the body of an FD predicate see Section 30 9 8 Goal Expanded Constraints page 297 a relation 3 expression expands to two indexicals each consisting of a switch 2 expression nested inside a unionof 3 expression Thus the following constraints are equivalent p X Y relation X 1 1 2 1 2 3 1 2 3 Y q Y X in unionof B dom Y switch B 1 1 2 3 2 2 3 3 3 Y in unionof B dom X switch B i1 1 2 1 2 3 1 2 3 30 9 3 Term Expressions A term expression has one of the following forms where T1 and T2 denote term expressions X denotes a variable I denotes an integer and S denotes the current store min X evaluates to the minimum of D X S max X evaluates to the maximum of D X S card X evaluates to the size of D X S X evaluates to the integer value of X A s
49. prefix is used to distinguish such calls from method calls Any prefixed directives occurring among the method clauses are also executed in the same source module For example to import into the source module and call the public predicates of a module the built in predicate use_module 2 and its variants may be used some_object use module library lists append 3 amp double list X XX append X X XX Fe 32 4 4 Super and Sub Two methods provided by the initial object object are super 1 and sub 1 Note that any definition of super 1 except the one in object is transformed to super 2 super 1 if sent to an object will return the immediate parents of the object sub 1 will return the immediate children of the object if any It is important to note that this service is provided only for objects that have object as their initial ancestor john super S S sub john sportsman professor S S no The sub 1 property allows programs to traverse object hierarchies from a root object object down to the leaves 336 SICStus Prolog 32 4 5 The Keyword Super To be able to send or delegate messages to the super objects in a convenient way while following the inheritance protocol the keyword super is provided The calls super method or super lt method mean send or delegate respectively method to the super objects according to the inheritance protocol A simple example illustrates this
50. vol 17 no 7 pp 57 13 Pergamon Press Ltd 1993 Ali amp Karlsson 92 K A M Ali and R Karlsson Scheduling Speculative work in MUSE and Performance Results International Journal of Parallel Programming Vol 21 No 6 December 1992 Aronsson 91 M Aronsson Methodology and Programming Techniques in GCLAII In Proceedings of the second Workshop on Extensions of Logic Programming ELP by Eriksson Hallnas and Schroeder Heister eds held at SICS Stockholm Sweden 1991 to be published in Lecture Notes in Artificial Intelligence Springer Verlag Also available as research report SICS R92 05 Aronsson 93 M Aronsson Implementational Issues in GCLA A Sufficiency and the Definiens op eration in Proceedings of the third Workshop on Extensions of Logic Programming ELP LNAI 660 Springer Verlag 1993 Beldiceanu amp Contejean 94 N Beldiceanu and E Contejean Introducing Global Constraints in CHIP Mathl Com put Modelling vol 20 no 12 pp 97 123 Pergamon Press Ltd 1994 Bryant 86 R E Bryant Graph Based Logarithms for Boolean Function Manipulation IEEE Trans on Computers August 1986 Carlsson 90 M Carlsson Design and Implementation of an OR Parallel Prolog Engine SICS Dis sertation Series 02 1990 Carreiro amp Gelernter 89a N Carreiro and D Gelernter Linda in Context Comm of the ACM 32 4 1989 Carreiro amp Gelernter 89b N Carreiro and D Gelernter How to Write Parall
51. which is adjusted to New max_workers The maximum number of Muse workers is returned This flag is read only worker_id The identity of the currently executing Muse workers is returned This flag is read only version The Muse version is returned The version can be plain or trace This flag is read only The following flags also exist but understanding them requires deep knowledge about the Muse scheduler and execution model so they are probably not useful for the average user vol_susp Used to turn voluntary suspension on 1 or off 0 vol_susp_time Voluntary suspension interval in milliseconds vol_susp_num Number of workers to voluntarily suspend vol_susp_avoid Controls the eagerness of voluntary suspension after resumption eager_cut Used to turn eager pruning on 1 or off 0 max_sch_loops Maximum number of scheduler loops 124 SICStus Prolog max_suspended Maximum number of megabytes for suspended branches muse_trace Goal muse_trace Goal FilePrefix The trace version generates a trace file for the goal Goal The file may be prefixed with FilePrefix The file is created in the current working directory if it can be written there or otherwise in the directory that is the value of the TMPDIR environment variable Cannot be executed in parallel when the execution changes the scheduler state 7 17 Miscellaneous X Y ISO Defined as if by the clause Z Z ie X and Y are unified length
52. which is is of the form variable denoting all constraints and rules or constraints Cs where Cs is one of variable denoting all constraints C 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 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 corresponding 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 Examples 320 SICStus Prolog 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 31 4 5 CHR Debugging Options page 320 31 4 4 CHR Debugging Messages All trace messages are output to t
53. 1 10 Saving and Restoring Program States Once a program has been read the system will have available all the information necessary for its execution This information is called a program state The state of a program may be saved on disk for future execution The state consists of all predicates and modules except built in predicates and clauses of volatile predicates the current operator declarations the values of all writable Prolog flags except debugging source_info and the user_ stream aliases see Section 7 6 State Info page 104 any blackboard data see Section 7 11 Blackboard Primitives page 116 internal database data see Section 7 10 Database page 115 and profiling data see Section 7 15 Profiling page 121 but no information for source linked debugging To save a program into a file File type the following directive On UNIX platforms the file becomes executable save_program File You can also specify a goal to be run when a saved program is restored This is done by save_program File start where start 0 is the predicate to be called Once a program has been saved into a file File the following directive will restore the system to the saved state restore File If a saved state has been moved or copied to another machine the path names of foreign resources and other files needed upon restore are typically different at restore time from their save time values To solve this prob
54. 100 amp wall color white amp floor surface wood F Another way to define apt_1 is by using attributes These can be retrieved and modified efficiently by the methods get 1 and set 1 respectively apt 1 4 super apartment amp attributes street name York Street number 100 wall_color white floor surface wood Chapter 32 Prolog Objects 331 32 2 3 Generic Objects for Easy Reuse Defining objects for easy reuse is a very important property for reducing the cost of large projects One important technique is to define prototypes in a parameterized way so that various instantia tions of a prototype correspond to different uses Parameterized or generic objects have been used for this purpose in other object oriented systems An object identifier can be a compound term The arguments of the term are parameters that are visible in the object body Here we show one example Other examples and techniques that use this facility has been investigated extensively in McCabe 92 The following is an object sort that sorts lists of different types sort has a parameter that defines the type of the elements of the list Notice that Type is visible to all methods in the body of sort and is used in the method partition 4 In the query we use sort rat to sort a list of terms denoting rational numbers We must therefore define a rat object and its lt method also rat A P Q lt R S PxS lt Q R sort
55. 155 The option S causes the SICStus Runtime Kernel to be statically linked into the executable thus eliminating the need to load these at runtime This produces a signif icantly larger executable Observe that this option has no effect on the resources and libraries spefified after by r and 1 Note This option is not available on Win32 The option help prints out usage info For example to compile and link a Runtime System ex_rt with the linked foreign resource ex statically linked first create the linked foreign resource see Section 8 2 7 Creating the Linked Foreign Resource page 135 using the static option Assuming the Runtime System s main program is in the file main c then type spmkrs ex rt c main c r ex If you prefer not to use the utility commands an alternative method is described in Chapter 38 Runtime Utilities page 373 8 8 4 Running the Executable To execute a Runtime System on a target machine you need the executable This is your application program created as described above the runtime kernel This is a shared object or a DLL usually SP_PATH libsprt37 so under UNIX or 4SP_PATH Nsprt37 dll under Windows the runtime library The saved state SP_PATH bin sprt sav contains the built in predicates written in Prolog It is restored into the program at runtime by the function SP_initialize your Prolog code Either as a saved state object code q1 fil
56. 2 i b d bc elena YU Up ide 215 erase lI oorisimaned4 eeu P gear wees 115 error exception l zz sweet Cete ek e we dla 69 lA AA eee 215 execution time profile_data 4 option 122 existence_error 5 error class 103 exp 1 EXPONE iia 96 exp 2 exponent sitiar eor ita 96 xpand O cae ied seeds dada 266 expand term 2 ix rna wake ie hove oe he 79 F fail debugger command esses esses 66 Tall sess nis Les te sss r4 AA ass eu 100 false Onn Li Ls ai 100 fcomplle741 vus ln be o EET CA ERREUR 52 75 fd clos re 2 rece Tr vue Dd Der De epe ve 286 fd dom 2 i o er e ERE A Ea hx RR RE 286 Edi global Si siot abso uds euet unde 286 fd ax 2 Fr uet o pre d i ntpote et baa s 286 Tamil v pe ada ee dada 286 SICStus Prolog fdzset O nes aic rmt ume du Pr olm e er 286 fd size 2 pu ter uy eet eee tera top DV ER 286 fd statistics 0 i ilg Riv res 283 fdostatistics 2 Lnd M ES eke hide NM 282 fdset_add_element 3 0 cece cece eee eee eee 288 fdset complement 2 sse 288 fdset del element 3 leeeeeess 288 fdset disjoint 2 upea tsn rug age ue eae 288 fdset eq 2 iie sme kd tent bd eccle Faces 288 fdset intersect 2 esee 288 fdset intersection 2 ccc eee 288 fdset intersection 3 0 cee eee eee 288 fdset interval 3 ccc cece ee 287 TAS CEM Dir rai vy e e aee eine CHER diee 287 fdset member 2 0 1 ieee cette ees 288 fdsetqnin 2
57. 3 array 2 E E array 2 yes aref1 Index Array Element Is as aref 3 except that Element is for undefined cells Example aref1 3 array 2 E E 0 yes array_to_list Array List List is a list with the pairs Index Element of all the elements of Array Example array_to_list array a b c d 2 List List 0 a 1 b 2 c 3 d yes 190 SICStus Prolog aset Index Array Element NewArray NewArray is the result of setting Array Index to Element Example aset 3 array 2 a Newarr Newarr array a 2 yes Chapter 13 Association Lists 191 13 Association Lists In this package finite mappings association lists are represented by AVL trees i e they are subject to the Adelson Velskii Landis balance criterion A tree is balanced iff for every node the heights of its two subtrees differ by at most 1 The empty tree is represented as t A tree with key K value V and left and right subtrees L and R is represented as t K V IRI ILI L R where IT denotes the height of T The advantage of this representation is that lookup insertion and deletion all become in the worst case O log n operations The algorithms are from Wirth 76 section 4 4 6 4 4 8 To load the package enter the query use module library assoc empty assoc Assoc Assoc is an empty AVL tree assoc to list
58. 7 Built In Predicates 87 If or 7 specifies a position preceding the current position the boundary is set at the current position NY Set a column boundary at line position N N defaults to the current posi tion CON Set a column boundary at N positions past the previous column boundary N defaults to 8 NU Specify padding in a column N is the fill character code N may also be specified as C where C is the fill character The default fill character is SPC Any t after the last column boundary on a line is ignored Example format t NICE TABLE t 61 n format tx 61 n O format t a 20 t a t 20 a t 20 t 61 n Right aligned Centered Left aligned format t d 20 t d t 20 d t 204 t 61 n 123 45 678 format t d 20 t d t 20 d t 204 t 61 n 1 2345 6789 format t 61 n O FRR k k kk kkk RRR KKK NICE TABLE 222628 2 28 ole ale 28 ok ok ok ok ok ok ok ok ale ok ok ale ak ok ok ok Right aligned Centered Left aligned 123 45 678 1 2345 6789 2K k K dd 3K 2K K 3K 2K 3K ok ok ok ok ok ok ok ok ok ok ok 3K 2K K 3K 2K 3K 3K K 3K 2K 3K ook 2K 2K ok ok ok ok ok 3K al 2K ook ok ok ok ok 3K OK ok OK ak 3K KK 7 1 4 Character Input Output There are two sets of character I O predicates The first set uses the current input and output streams while the second set always uses the standard input and output streams
59. A ES 14 escape sequence lesse eene 106 401 exception handling 02 69 101 exception handling in C 00 e cece 144 execution ci eet a Meee Perens eee 15 execution profiling 0 i kirri n naa 121 execution nested 0 00 0 e eee e eee eee 16 unu PEE 16 expansion MACIOS r oa an E nnne 79 SICStus Prolog expansion module name 49 56 exported predicaten cenni aneda e a e 47 external database oooooooccoooccorrcccrcc ro 235 external storage c i 235 F failure deep vs cea i EP on 122 178 failure shallow ooooooomommmoo 122 178 fcompile considerations for oooooocoooommo o 58 ED predicates iria aa AIR 293 EDS ata cats a e Debes 287 Me A RE ia 71 file name alias iue ct y ee ike wee vd 12 89 file module ed reote pere e emet 48 filename oos SER abi dio E PRI 72 Finding Libraries li d ui rS V ieoi 9 Finding Shared Objects 0 0c eee e eee 9 finite domain bl RR vH 272 flag Prolog ics Rr te nr E 105 108 floab se io ADA A e GEA 27 HU ei pe ds 35 foreign language interface 127 128 foreign T SOUIQG a iyne eeni tid eee hd epus 128 foreign resource linked 0 128 135 function prototype 0 2 cece eee ee 6 f netoE as rs Bik ved Peed aes tu a rye au 28 G garbage collection lisse 106 PAU PC tn cioe seu oe en RT EE a
60. A syntax error was found when reading a term with read 1 2 This error is raised only if the syntax_errors flag see prolog_flag 3 is set to error representation_error Goal ArgNo ErrorType A representation error occurs when the program tries to compute some well defined value which cannot be represented such as a compound term with arity gt 255 consistency error Goal Culprit 1 Culprit2 Message A consistency error occurs when two otherwise valid values or operations have been specified which are inconsistent with each other system error Message An error occurred while dealing with the operating system It is possible to handle a particular kind of existence errors locally calls to undefined predicates This can be done by defining clauses for unknown predicate handler Goal Module NewGoal user unknown predicate handler Goal Module NewGoal A hook predicate This predicate is called as a result of a call to an undefined predicate Goal is bound to the goal of the undefined predicate and Module to the module where the call was made If this predicate succeeds Module NewGoal is called otherwise the action taken is governed by the unknown Prolog flag The following example shows an auto loader for library packages 104 SICStus Prolog user unknown predicate handler Goal Module Goal functor Goal Name Arity require Module Name Arity 7 6 Information about the State of the Program lis
61. Assoc List List is a list of Key Value pairs in ascending order with no duplicate Keys specifying the same finite function as the association tree Assoc Use this to convert an association tree to a list is_assoc Assoc Assoc is a proper AVL tree It checks both that the keys are in ascending order and that Assoc is properly balanced min_assoc Assoc Key Val Key is the smallest key in Assoc and Val is its value max_assoc Assoc Key Val Key is the greatest key in Assoc and Val is its value gen assoc Key Assoc Value Key is associated with Value in the association tree Assoc Can be used to enumerate all Values by ascending Keys get_assoc Key Assoc Value Key is identical to one of the keys in the association tree Assoc and Value unifies with the associated value get_assoc Key OldAssoc OldValue NewAssoc New Value OldAssoc and NewAssoc are association trees of the same shape having the same elements except that the value for Key in OldAssoc is OldValue and the value for Key in NewAssoc is NewValue get_next_assoc Key Assoc Knext Vnext Knext and Vnext is the next key and associated value after Key in Assoc 192 SICStus Prolog get_prev_assoc Key Assoc Kprev Vprev Kprev and Vprev is the previous key and associated value after Key in Assoc list to assoc List Assoc List is a proper list of Key Value pairs in any order and Assoc is an association tree specifyin
62. Box model of Prolog execution views program control flow in terms of movement about the program text This model provides a basis for the debugging mechanism in Development Systems and enables the user to view the behavior of the program in a consistent way Let us look at an example Prolog predicate 60 SICStus Prolog AZ Call Exit Serr AE gt descendant X Y offspring X Y gt descendant X Z gt offspring X Y descendant Y Z Fail Redo x 4 lt Exception The first clause states that Y is a descendant of X if Y is an offspring of X and the second clause states that Z is a descendant of X if Y is an offspring of X and if Z is a descendant of Y In the diagram a box has been drawn around the whole predicate and labeled arrows indicate the control flow in and out of this box There are five such arrows which we shall look at in turn Call This arrow represents initial invocation of the predicate When a goal of the form descendant X Y is required to be satisfied control passes through the Call port of the descendant box with the intention of matching a component clause and then satisfying any subgoals in the body of that clause Note that this is independent of whether such a match is possible i e first the box is called and then the attempt to match takes place Textually we can imagine moving to
63. C halt Code Halts Prolog immediately returning Code help Hookable prints a help message not available in Runtime Systems if P Q R If P then Q else R exploring all solutions of P incore Term Executes the procedure call Term Summary of Built In Predicates 385 initialization Executes a list of user defined goals not available in Runtime Systems initialization Goal Adds Goal to the list of goals executed by initialization O not available in Runtime Systems instance Ref Term Term is a most general instance of the record or clause uniquely identified by Ref integer X X is currently instantiated to an integer Y is X Y is the value of the arithmetic expression X is mutable X X is currently instantiated to a mutable term keysort List1 List2 The list List1 sorted by key yields List2 leash Mode Sets leashing mode to Mode not available in Runtime Systems length List Length The length of list List is Length library directory Directory user library directory Directory A hook predicate telling how to expand library File file names line count 4 Stream N N is the number of lines read written on stream Stream line position 4Stream N N is the number of characters read written on the current line of Stream link foreign resource Resource SourceFile Option CFiles ObjectFiles Libraries Builds a linked foreign resource not ava
64. C on on D db 1411928 no db_close Chapter 27 External Storage of Terms External Database 239 27 6 The Db Spec A db spec is on of the following terms e the atom on or e the atom off or e a structure with functor on or off and every argument being a db spec The following table defines the way indices are calculated a bit more formally The table defines the index as a function INDEX of the db spec and the indexed term The column Index Calculation describes the procedure a yes means that some primitive function is used such as a hash function INDEX s t means simply that the function definition the table is applied again but with a new db spec s and a new term t I means on or off DB Spec Indexed Term Index Calculation off any no on any yes on principal functor IC atomic yes IC variable yes I S1 52 Sn F A1 A2 Am yes on principal functor INDEX Si Ai for 1 lt i lt min n m Every term is stored together with a set of keywords for indexing purposes The space overhead is approximately 16 bytes per keyword per term The number of keywords stored depends on the db spec and on the term being indexed The following table defines the number of keywords as a function K of the db spec and the indexed term DB Spec Indexed Term Number of keywords off any 0 on any 2 IC atomic 2 TG variable 2 I S1 Sn F Al Am 1 K S1 A1 K Sj Aj j min n m
65. CFunctionName is the name of a C function Predi cate specifies the name of the Prolog predicate that will be used to call CFunction Predicate also specifies how the predicate arguments are to be translated into the cor responding C arguments This predicate should be defined entirely in terms of facts unit clauses For example foreign pos cursor c move cursor integer integer The above example says that the C function pos cursor has two integer value arguments and that we will use the predicate move cursor 2 to call this function A goal move cursor 5 23 would translate into the C call pos cursor 5 23 The third argument of the predicate foreign 3 specifies how to translate between Prolog arguments and C arguments call to a foreign predicate will raise an exception if an input arguments is uninstantiated instantiation_error 2 or has the wrong 130 SICStus Prolog type type_error 4 or domain domain_error 4 The call will fail upon return from the function if the output arguments do not unify with the actual arguments The available conversions are listed in the next subsection 8 2 4 Conversions between Prolog Arguments and C Types The following table lists the possible values for the arguments in the predicate specification of foreign 2 3 The value declares which conversion between corresponding Prolog argument and C type will take place Prolog integer C long The argument should be a number It i
66. Head 10 5 7 Prolog in Prolog This example shows how simple it is to write a Prolog interpreter in Prolog and illustrates the use of a variable goal In this mini interpreter goals and clauses are represented as ordinary Prolog data structures i e terms Terms representing clauses are specified using the predicate my_clause 1 e g Chapter 10 Programming Tips and Examples 183 my_clause grandparent X Z parent X Y parent Y Z A unit clause will be represented by a term such as my clause parent john mary true The mini interpreter consists of three clauses execute P Q execute P execute Q execute P predicate property P built in P execute P my_clause P Q execute Q The second clause enables the mini interpreter to cope with calls to ordinary Prolog predicates e g built in predicates The mini interpreter needs to be extended to cope with the other control structures i e P Q P gt Q P gt Q R A P and if P Q R 10 5 8 Translating English Sentences into Logic Formulae The following example of a definite clause grammar defines in a formal way the traditional mapping of simple English sentences into formulae of classical logic By way of illustration if the sentence Every man that lives loves a woman is parsed as a sentence by the call phrase sentence P every man that lives loves a woman then P will get instantiated to all X man
67. Kernel and development system extensions to be statically linked into the executable thus eliminating the need to load these at runtime This produces a significantly larger executable Observe that this option has no effect on the resources Note This option is not available on Win32 The option help prints out usage info For example to compile and link a Development System ex_stat with the linked foreign resource ex statically linked first create the linked foreign resource see Section 8 2 7 Creating the Linked Foreign Resource page 135 using the static option Then type spmkds ex stat ex The executable can then be run as sicstus base ex stat and optionally more command line options as for the standard sicstus command The generated executable will run the usual Prolog top level and the full develoment environment is available as usual 8 10 Examples Chapter 8 Mixing C and Prolog 157 8 10 1 Train Example connections This is an example of how to create a Runtime System The Prolog program train p1l will display a route from one train station to another The C program train c calls the Prolog code and writes out all the routes found between two stations train pl connected From To Path connected From To Path From connected To To To _ connected From To From Path Visited connection From Via connection Via From not_visited Visited Via conn
68. List Element Element is the Nth element of List The first element is number 1 Example nth N a b c d e f g h i f N 6 yes nth N List Element Rest Element is in position N in the List and Rest is all elements in List except Element nthO N List Element Element is the Nth element of List counting the first element as 0 nthO N List Element Rest Element is the Nth element of List counting the first element as 0 Rest is all the other elements in List Example nthO N a b c d e f g h i j f R N 5 R a b c d e g h i j yes Chapter 16 List Operations 203 permutation List Perm Perm is a permutation of List prefix Prefix List Prefix is a prefix of List Example prefix 1 2 31 1 2 3 4 5 6 yes remove_duplicates List Pruned Pruned is the result of removing all identical duplicate elements in List Example remove_duplicates 1 2 3 2 3 1 P P 1 2 3 no reverse List Reversed Reversed has the same elements as List but in a reversed order same length Listl List2 Listl and List2 have the same number of elements same length Listl List2 Length List1 and List2 have the same number of elements and that number is Length Exam ple same length 1 2 3 9 8 7 N no select Element List List2 The result of removing an occurrence of Element in List is List2 sublist Sub List Sub contains
69. Permissions Permissions is an atom an integer see access 2 or a list of atoms and or integers The atoms must be drawn from the list read write search exists file property FileName Property FileName has the property Property The possible properties are type Type Type is one of regular directory fifo symlink socket or unknown size Size Size is the size of FileName mod_time ModTime ModTime is the time of the last modification of FileName If Property is uninstantiated the predicate will enumerate the properties on backtrack ing host_id HID HID is the unique identifier represented by an atom of the host executing the current SICStus Prolog process host_name HostName HostName is the standard host name of the host executing the current SICStus Prolog process pid PID PID is the identifier of the current SICStus Prolog process ki11 Pid Signal Sends the signal Signal to process Pid mktemp Template FileName Interface to the UNIX function mktemp 3 A unique file name is created and unified with FileName Template should contain a file name with six trailing Xs The unique file name is that template with the six Xs replaced by a character string Chapter 21 Operating System Utilities 217 popen Command Mode Stream Interface to the UNIX function popen 3 Passes Command to a new default shell process for execution Mode may be either read or write In the former case the
70. RET The only option which you really have to remember is h followed by RET This provides help in the form of the following list of available options RET RET B 89 ctOQ Hh HuiOo0 0n H gt A Oo COW ux creep c creep leap Z zip skip s lt i gt skip i out o lt n gt out n q skip q lt i gt q skip i retry r lt i gt retry i fail f lt i gt fail i display W write print p lt i gt print partial ancestors g lt n gt ancestors n backtrace t lt n gt backtrace n blocked goals amp lt n gt nth blocked goal nodebug debugging spy this lt i gt spy conditionally nospy this a find this abort b break command u unify raise exception reset printdepth lt lt n gt set printdepth reset subterm lt n gt set subterm help h help creep causes the debugger to single step to the very next port and print a message Then if the port is leashed see Section 6 2 Basic Debug page 61 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 running 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 All you need to do is to set spy points on an evenly spread set of pertinent predicates a
71. Stefan Andersson Kent Boortz Per rand Goran Bage Mats Carlsson Jesper Eskilson Lena Flood Seif Haridi Ralph Haygood Christian Holzbaur Key Hyckenberg Hans Nilsson Mats Nyl n Greger Ottosson Dan Sahlin Thomas Sj land Johan Wid n and Emil Astr m The OR parallel execution model and parallelization of SICStus Prolog are due to Khayri A M Ali and Roland Karlsson The Industrialization of SICStus Prolog 1988 1991 was funded by Ericsson Telecom AB NobelTech Systems AB Infologics AB and Televerket under the National Swedish Information Technology Program ITA The development of release 3 1991 1995 was funded in part by Ellemtel Utvecklings AB This manual is based on DECsystem 10 Prolog User s Manual by D L Bowen L Byrd F C N Pereira L M Pereira D H D Warren The Visandor visualization tool was developed at the Technical University of Madrid and its inclusion into this distribution was kindly permitted by Manuel Hermenegildo See Chapter 29 CLPQR page 247 for acknowledgments relevant to the clp Q R constraint solver See Chapter 30 CLPFD page 271 for acknowledgments relevant to the clp FD constraint solver Quintus and Quintus Prolog are trademarks of Quintus Computer Systems Inc UNIX is a trade mark of Bell Laboratories DEC is a trademark of Digital Equipment Corporation Intel is a trademark of Intel Corp Microsoft and Windows are trademarks of Microsoft Corp OS 2 is a trademark of IBM Cor
72. The effect of executing a goal is to enumerate one by one its true instances Here then is an informal definition of the procedural semantics We first illustrate the semantics by the simple query concatenate X Y a b We find that it matches the head of the first clause for concatenate 3 with X instantiated to al X1 The new variable X1 is constrained by the new query produced which contains a single recursive procedure call concatenate X1 Y b Again this goal matches the first clause instantiating X1 to b X2 and yielding the new query concatenate X2 Y Now the single goal will only match the second clause instantiating both X2 and Y to Since there are no further goals to be executed we have a solution X a b Y 0 i e a true instance of the original goal is concatenate a b a b If this solution is rejected backtracking will generate the further solutions X a Y b X Y a b in that order by re matching against the second clause for concatenate goals already solved once using the first clause Thus in the procedural semantics the set of clauses H Bl Bm H Bl Bm are regarded as a procedure definition for some predicate H and in a query Chapter 2 The Prolog Language 35 Gl Gn each Gi is regarded as a procedure call To execute a query the system selects by its computation rule a goal Gj say and searc
73. Type use module library lists append 3 amp qsort amp qsort PIL S partition L P Small Large qsort Small S0 qsort Large 1 append SO P S1 S amp partition _P amp partition X L1 1 P Small Large Type X lt P gt Small X Smalli Large Largel Small Smalli Large X Large1 partition L1 P Smalli Largel sort rat qsort 23 3 34 11 45 17 L L 45 17 34 11 23 3 Parameterized objects are interesting in their own right in Prolog even if one is not interested in the object oriented paradigm They provide global context variables in a Prolog program without having to add such variables as additional context arguments to each clause that potentially uses the context 332 SICStus Prolog 32 3 Self Message Sending and Message Delegation In Prolog Objects each method is executed in the context of an object This object may not be the static object where the method is declared The current contextual object is used to determine dynamically which attributes are accessed and which methods are called This leads to a mechanism known as dynamic binding This object can be retrieved using the universal method self S where S will be bound to the current contextual object When a message is sent to an object the corresponding method will be executed in the context of the target object A message delegated to an object will in
74. Vertices Unifies Vertices with the vertices in Graph edges Graph Edges Unifies Edges with the edges in Graph add vertices Graphl Vertices Graph2 Graph2 is Graph1 with Vertices added to it 222 SICStus Prolog del vertices Graphl Vertices Graph2 Graph2 is Graph1 with Vertices and all edges to and from them removed from it add edges Graph1 Edges Graph2 Graph2 is Graph1 with Edges and their to and from vertices added to it del edges Graphl Edges Graph2 Graph2 is Graph1 with Edges removed from it transpose Graph Transpose Transpose is the graph computed by replacing each edge u v in Graph by its sym metric edge v u Takes O N 2 time neighbors Vertex Graph Neighbors neighbours Vertex Graph Neighbors Vertex is a vertex in Graph and Neighbors are its neighbors complement Graph Complement Complement is the complement graph of Graph ie the graph that has the same vertices as Graph but only the edges that are not in Graph compose G1 G2 Composition Computes Composition as the composition of two graphs which need not have the same set of vertices transitive_closure Graph Closure Computes Closure as the transitive closure of Graph in O N 3 time symmetric closure Graph Closure Computes Closure as the symmetric closure of Graph i e for each edge u v in Graph add its symmetric edge v u Takes O N 2 time This is useful for m
75. Xs Set X in_set Set Ps eq_all Xs Set Ps end_of_file sample queries exactly 5 A B C 1 A 5 A 5 B in inf 4 6 sup C in inf 4 6 sup exactly 5 A B C1 1 A in 1 2 B in 3 4 C 5 A in 1 2 B in 3 4 30 9 Defining Primitive Constraints Indexicals are the principal means of defining constraints but it is usually not necessary to resort to this level of programming most commonly used constraints are available in a library and or via macro expansion l he key feature about indexicals is that they give the programmer precise control over aspects of the operational semantics of the constraints Trade offs can be made between the computational cost of the constraints and their pruning power The indexical language provides many degrees of freedom for the user to select the level of consistency to be maintained depending on application specific needs Chapter 30 Constraint Logic Programming over Finite Domains 291 30 9 1 Indexicals An indexical is a reactive functional rule of the form X in R where R is a set valued range expression see below See Syntax of Indexicals page 301 for a grammar defining indexicals and range expressions Indexicals can play one of two roles propagating indexicals are used for constraint solving and checking indexicals are used for entailment checking When a propagating indexical fires R is evaluated in the current store S which is extended by ad
76. a default help message printed on the current output stream This predicate is not available in Runtime Systems help A hook predicate This may be defined by the user to print a help message on the current output stream Chapter 8 Mixing C and Prolog 127 8 Mixing C and Prolog SICStus Prolog provides a bi directional procedural interface for program parts written in C and Prolog The C side of the interface defines a number of functions and macros for various operations On the Prolog side you have to supply declarations specifying the names and argument value types of C functions being called as Prolog predicates These declarations are used by the predicate load_ foreign_resource 1 which performs the actual binding of C functions to Prolog predicates In most cases the argument value type declaration suffice for making the necessary conversions of data automatically as they are passed between C and Prolog However it is possible to declare the type of an argument to be a Prolog term in which case the receiving function will see it as a handle object called an SP_term_ref for which access functions are provided The C support routines are available in a Development System as well as in Runtime Systems The support routines include e Static and dynamic linking of C code into the Prolog environment e Automatic conversion between Prolog terms and C data with foreign 2 3 declarations e Functions for accessing and creat
77. a set of Prolog files for use in a statically linked executable Note this is provided for backwards compatibility only We recommend using foreign resources instead which can be dynamically linked generate_flinkage Files Files are loaded as by use_module 1 Calls to load_foreign_files 2 are intercepted by means of the goal expansion mechanism The file flinkage c is generated out of the declarations found Finally compile and link the flinkage c file with the user code libraries and the runtime and optionally the development kernel The following predicates available in Development Systems only provide alternative methods to building executables or linked foreign resources compared to the methods described in Section 8 8 3 Creating the Executable page 154 Section 8 9 Development Systems page 156 and Section 8 2 7 Creating the Linked Foreign Resource page 135 If the default method doesn t work as expected for some reason or you wish to use an Integrated Development Environment etc the following outlines the necessary steps To build an executable First decide which foreign resources are to be statically linked and create a resource table file as follows prepare_resource_table ResourceNames CFile where ResourceNames is a list of the resource names and CFile is the file where to write the generated code The next step is to create linked foreign resources from the foreign resources which are to be stati
78. also produce numerical differences between the text in this manual and the actual results of clp R for a given edition of the software 29 2 1 Solver Predicates The solver interface for both Q and R consists 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 Use the module prefix to distinguish the solvers if both clp Q and clp R were loaded clpr Ar Br 10 Ar Br clpq 1Aq Bq 107 Aq Bq Aq 5 Ar 5 0 Bq 5 Br 5 0 Chapter 29 Constraint Logic Programming over Rationals or Reals 249 Although clp Q and clp R are independent modules you are asking for trouble if you accidently share variables between them clpr A B 10 clpq A B TYPE ERROR _118 5 0 arg 2 expected a rational number found 5 0 This is because both solvers eventually compute values for the variables and Reals are incompatible with Rationals Here is the constraint grammar Constraint gt C IC C conjunction C gt Expr Expr equation Expr Expr equation Expr lt Expr strict inequation Expr gt Expr strict inequation Expr lt Expr nonstrict inequation Expr gt Expr nonstrict inequation Expr Expr disequation Expr gt variable Prolog variable number floating point or integer Expr unary plus
79. an object date from which we can get the current date borrow Person history_item _Person0 Status _Date0 Status returned gt date current Date asserta history_item Person borrowed Date display book not available ttynl amp 338 SICStus Prolog 32 4 9 Inheritance of Dynamic Behavior When an object is created it will inherit from its parents their dynamic behavior Methods that are declared dynamic in a parent will be copied into the object and its dynamic behavior preserved a A super object amp dynamic p 1 amp p 1 amp p 2 prit super a b p X X217 X227 no b asserta p 3 yes b p X X237 A217 X 27 no Notice that by redeclaring a method to be dynamic in a sub object amounts to redefining the method and overriding of the parent definition will take effect C F super a amp dynamic p 1 c p X no 32 5 Creating Objects Dynamically As with dynamically declared objects the full flexibility of Prolog Objects is achieved when objects are created at runtime Anything except the inheritance hierarchy can be changed methods can be added or deleted The services for object creation destruction and method modification are defined in the proto object object Chapter 32 Prolog Objects 339 32 5 1 Object Creation SomeObject new NewObject NewObject is created with SomeObject as super NewObject could be an atom
80. and only the elements of Set1 which are not also in Set2 Ex ample ord subtract 1 2 3 4 3 4 5 6 S S 1 2 yes ord symdiff Set1 Set2 Difference Difference is the symmetric difference of Set1 and Set2 Example ord_symdiff 1 2 3 4 3 4 5 6 D D 1 2 5 6 yes ord_union Set1 Set2 Union Union is the union of Set1 and Set2 ord_union Set1 Set2 Union New Union is the union of Set1 and Set2 and New is the difference between Set2 and Set1 This is useful if you are accumulating members of a set and you want to process new elements as they are added to the set Chapter 18 Ordered Set Operations ord_union Sets Union Union is the union of all the sets in Sets Example ord union 1 2 3 2 3 41 3 4 5 U U 1 2 3 4 5 yes 209 210 SICStus Prolog Chapter 19 Queue Operations 211 19 Queue Operations A queue is a first in first out store of information This implementation of queues uses difference lists the head of the difference list represents the beginning of the queue and the tail represents the end of the queue The members of the difference list are the elements in the queue The first argument in the queue representation is the number of elements in the queue in unary representa tion Thus a queue with n elements is represented as follows qd 8 8 00 20 X1 Xn Y1 Ym Y1 Ym where n is the length of the queue and X1
81. application for describing its domain animal 4 super object amp relative size 8 size Obj_size super 0bj prototype 0bj prototype size Prototype size S is Obj_size Prototype_size 100 ds bird super animal amp moving method fly amp active at daylight albatross super bird amp color black_and_white amp size 115 kiwi 4 super bird amp moving_method walk amp active_at night amp size 40 amp color brown albert super albatross amp size 120 Jis ross super albatross amp size 40 ross relative_size R Chapter 32 Prolog Objects 351 R 34 78 32 10 2 Inheritance and Delegation The following example illustrates a number of concepts Firstly how to use Prolog Objects for defining traditional classes a la Smalltalk or other traditional object oriented languages Secondly how to create instances of these classes Finally how to access instance variables The concept of instance variables is readily available as the variables belonging to the instances created dynamically and not to the class of the instances For example each instance of the class point will have two instance variables x and y represented by the attributes x 1 and y 1 The traditional class variables are easily available by accessing the same attributes in the associated class Another issue is the pattern used to create new instanc
82. are somehow generated e g by reading them from a stream until some test becomes true Usually generate action and test are all determinate Repeat loops cannot contribute to the logic of the program They are only meaningful if the action involves side effects The only reason for using repeat loops instead of a more natural tail recursive formu lation is efficiency when the test fails back the Prolog engine immediately reclaims any working storage consumed since the call to repeat 0 call Term ISO incore Term Term If Term is instantiated to a term which would be acceptable as the body of a clause then the goal ca11 Term is executed exactly as if that term appeared textually in its place except that any cut occurring in Term only cuts alternatives in the execution of Term Use of incore 1 is not recommended If Term is not instantiated as described above an error message is printed and the call fails Chapter 7 Built In Predicates 101 call cleanup Goal Cleanup This construction can be used to ensure that Cleanup is executed as soon as Goal has completed execution no matter how it finishes In more detail When call cleanup 2 with a continuation C is called or backtracked into first Goal is called or backtracked into Then there are four possibilities 1 Goal succeeds deterministically possibly leaving some blocked subgoals Cleanup is executed with continuation C 2 Goal succeeds with some alt
83. 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 31 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 Chapter 31 Constraint Handling Rules 317 31 4 1 Control Flow Model The entities reflected by the CHR debugger are constraints and rules Constraints are 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 reconsidered port wake when variables are touched The execution of a constraint consists of trying to apply the rules mentioning the constraint 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 th
84. 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 ie all constraints not yet exited that led to the current constraint in the derivation sequence The format is the same as with trace messages 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 322 SICStus Prolog O0 call primes 10 lt c1 gt 1 1 try eratosthenes rule 2 primes 10 lt c1 gt g Ancestors 1 call primes 10 lt c1 gt 1 1 try eratosthenes rule 2 primes 10 lt c1 gt 1 1apply 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 primes 10 lt c1 gt 2 call prime 10 lt c2 gt print constraints prints a list of the constraints in the constraint store With a numeric argument details relevant primarily to CHR implementors are shown nodebug switches the CHR debugger off debuggin
85. be converted to a Prolog list of character codes Prolog string C char F The C function should return a char The returned string will be converted to a Prolog atom Prolog will copy the string to a safe place so the memory occupied by the returned string may be reused during subsequent calls to foreign code Prolog string N C char F The C function should return a char The first N characters of the string will be copied and the copied string will be stripped of trailing blanks The stripped string will be converted to a Prolog atom C may reuse or destroy the string buffer during later calls Prolog address C void F The C function should return a void The returned value which is constrained according to see Section 8 3 2 Creating Prolog Terms page 137 SP put address will be converted to a Prolog integer Prolog address TypeName Chapter 8 Mixing C and Prolog 133 C TypeName F The C function should return a TypeName The returned value which is constrained according to see Section 8 3 2 Creating Prolog Terms page 137 SP_put_address will be converted to a Prolog integer Prolog term C SP term ref F The C function should return an SP term ref Prolog will try to unify its value with the actual argument 8 2 5 Interface Predicates In the following descriptions the Resource argument is an unsuffixed file specification of a linked foreign resource
86. be loaded it is sometimes necessary to tell the system to treat some of the predicates specially This information is supplied by including declarations about such predicates in the source file preceding any clauses for the predicates which they concern A declaration is written just as a command beginning with A declaration is effective from its occurrence through the end of file Although declarations that affect more than one predicate may be collapsed into a single declaration the recommended style is to write the declarations for a predicate immediately before its first clause Operator declarations are not declarations proper but rather commands that modify the global table of syntax operators Operator declarations are executed as they are encountered while loading programs The rest of this section details the available forms of predicate declarations 54 SICStus Prolog 5 2 1 Multifile Declarations A declaration multifile PredSpec PredSpec where each PredSpec is a predicate spec causes the specified predicates to become multifile This means that if more clauses are subsequently loaded from other files for the same predicate then the new clauses will not replace the old ones but will be added at the end instead As of release 3 multifile declarations are required in all files from where clauses to a multifile predicate are loaded An example when multifile declarations are particularly useful is in de
87. benchmark suite is run by typing compile library clpfd examples bench bench 30 10 1 Send More Money Let us return briefly to the Send More Money problem see Section 30 2 2 A Constraint Satisfaction Problem page 273 Its sum 8 predicate will expand to a space efficient conjunction of library constraints A faster but more memory consuming version is defined simply by changing the neck symbol of sum 8 from to thus turning it into an FD predicate sum S E N D M O R Y 1000 S 100 E 10 N D 1000 M 100 0 10 R E 10000 M 1000 0 100 N 10 E Y 30 10 2 N Queens The problem is to place N queens on an NxN chess board so that no queen is threatened by another queen The variables of this problem are the N queens Each queen has a designated row The problem is to select a column for it The main constraint of this problem is that no queen threaten another This is encoded by the no_threat 3 constraint and holds between all pairs X Y of queens It could be defined as no_threat X Y I X Y X4I Y X I Y However this formulation introduces new temporary domain variables and creates twelve fine grained indexicals Worse the arithmetic constraints are only guaranteed to maintain interval consistency and so may miss some opportunities for pruning elements in the middle of domains A better idea is to formulate no threat 3 as an FD predicate with t
88. body gr body gr body Full Prolog Syntax 397 gr body gr body non terminal terminals gr condition non terminal term 1 where term is not otherwise a gr body terminals gt list string gr condition body module atom Syntax of Terms as Tokens term read in subterm 1200 full stop subterm N term M where M is less than or equal to N term N op N fx subterm N 1 except in the case of a number if subterm starts with a op must be followed by layout text op N fy subterm N if subterm starts with a op must be followed by layout text Y 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 term 1000 subterm 999 subterm 1000 term 0 gt functor arguments provided there is no layout text between the functor and the Csubterm 1200 4 subterm 1200 Y list string constant variable op N T name 398 SICStus Prolog where name has been declared as an operator of type T and precedence N arguments subterm 999 subterm 999 arguments list listexpr listexpr subterm 999 subterm 999 listexpr subterm 999 subterm 999 constant atom number number unsigned number sign unsigned number sign inf sign nan unsigned number gt natural number u
89. break and go back to the old execution However any changes to the leashing or to spy points will remain in effect command gives you the ability to call arbitrary Prolog goals It is effectively a one off break see above The initial message will be output on the standard error stream and a command is then read from the standard input stream and executed as if you were at top level unify is available at the Call port and gives you the option of providing a solution to the goal from the standard input stream rather than executing the goal This is convenient e g for providing a stub for a predicate that has not yet been written A prompt will be output on the standard error stream and the solution is then read from the standard input stream and unified with the goal raise exception is available at all ports A prompt will be output on the standard error stream and an exception term is then read from the standard input stream and raised in the program being debugged This command without arguments resets the printdepth to 10 With an argument of n the printdepth is set to n treating 0 as infinity While at a particular port a current subterm of the current goal is maintained It is the current subterm which is displayed printed or written when prompting for a debugger command Used in combination with the printdepth this provides a means for navigating in the current goal for focusing on the part which is of intere
90. by any edges vertices WeightedGraph Vertices Unifies Vertices with the vertices in WeightedGraph edges WeightedGraph Edges Unifies Edges with the edges in WeightedGraph 226 SICStus Prolog add_vertices WeightedGraph1 Vertices WeightedGraph2 WeightedGraph2 is WeightedGraphl with Vertices added to it del vertices WeightedGraphl Vertices WeightedGraph2 WeightedGraph2 is WeightedGraphl with Vertices and all edges to and from them removed from it add edges WeightedGraph1 Edges WeightedGraph2 WeightedGraph2 is WeightedGraphl with Edges and their to and from vertices added to it del edges WeightedGraph1 Edges WeightedGraph2 WeightedGraph2 is WeightedGraphl with Edges removed from it transpose WeightedGraph Transpose Transpose is the graph computed by replacing each edge u v in WeightedGraph by its symmetric edge v u It can only be used one way around Takes O N 2 time neighbors Vertex WeightedGraph Neighbors neighbours Vertex WeightedGraph Neighbors Vertex is a vertex in WeightedGraph and Neighbors are its weighted neighbors transitive_closure WeightedGraph Closure Computes Closure as the transitive closure of WeightedGraph in O N 3 time symmetric closure WeightedGraph Closure Computes Closure as the symmetric closure of WeightedGraph i e for each edge u v in WeightedGraph add its symmetric edge v u Takes O N 2 time T
91. callback Returns non zero iff installation succeeded func is called with arg as first argument A queue of functions with corresponding arguments is maintained that is if several calls to SP_ event occur before Prolog can a accept an interrupt the functions are queued and executed in turn at the next possible opportunity Note that the queuing facility is only safe for signal handlers installed using SP signal O see below Depending on the value returned from func the interrupted Prolog execution will just continue SP_ SUCCESS or backtrack SP FAILURE or SP ERROR An exception raised by func will be processed in the interrupted Prolog execution In case of fail or exception the event queue is flushed Chapter 8 Mixing C and Prolog 143 int SP_event int func void arg A signal handler having called SP event should call SP_continue as its last action to ensure that the interrupt is processed as early as possible void SP continue To install a function func as a handler for the signal sig call void SP signal int sig void func O 0 SP signal will also if permitted by the operating system add sig to a set of signals which are all blocked during the handling of the event queue Some operating systems require that void SP reinstall signal int sig void func O 0 be called from a signal handler to unblock or reinstall the handler This function should be called before SP continue T
92. chr nodebug chr debugging Prints onto the standard error stream information about the current CHR debugging 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 318 chr_leash Mode SICStus Prolog 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 exit redo fail wake try apply insert remove Prompt when a constraint is executed for the first time Prompt when the constraint is successfully processed i e the applicable rules have applied Prompt at subsequent exits generated by non deterministic rule bodies Prompt when a constraint fails Prompt when a constraint from the constraint store is woken and recon sidered because one of its variables has been touched Prompt just before the guard evaluation of a rule after constraints match ing the heads have been found Prompt upon the application of a rule after the successful guard evalua tion when the rule commits and fires just before evaluating the body Prompt when a constraint gets
93. clauses whose head matches Head where Head must be instantiated to an atom or a compound term The predicate concerned must currently be dynamic The predicate definition is retained Note all predicates mentioned above first look for a predicate that is visible in the module in which the call textually appears If no predicate is found a new dynamic predicate with no clauses is created automatically During OR parallel execution however predicates must not be defined on the fly like this It is recommended to declare as dynamic predicates for which clauses will be asserted abolish Spec ISO abolish Name Arity Erases all clauses of the predicate specified by Spec or Name Arity Spec has the same form as for spy 1 see Section 6 3 Spy Point page 62 and Name may be prefixed by a module name see Section 4 2 Module Spec page 48 The predicate definition and all associated information such as spy points is also erased The predicates concerned must all be user defined erase Ref The dynamic clause or recorded term see Section 7 10 Database page 115 whose implementation defined identifier is Ref is effectively erased from the internal database or interpreted program instance Ref Term A most general instance of the dynamic clause or recorded term whose implementation defined identifier is Ref is unified with Term Ref must be instan tiated to a legal identifier 7 10 Internal Database The predicates des
94. complete version is provided by the all_distinct 1 constraint see below The following constraint is a complete version of the all_different 1 constraint The algorithm is due to Regin Regin 94 all_distinct Variables where Variables is a list of domain variables or integers Each variable is constrained to take a value that is unique among the variables The implementation is complete i e it maintains domain consistency see Section 30 7 The Constraint System page 283 The following is a constraint over two lists of length n of variables Each variable is constrained to take a value in 1 n that is unique for its list Furthermore the lists are dual in a sense described below assignment Xs Ys where Xs and Ys are lists of domain variables or integers both of length n True if all Xi Yi in 1 n and Xi j iff Yj i The following constraint can be thought of as constraining n nodes in a graph to form a Hamiltonian circuit The nodes are numbered from 1 to n The circuit starts in node 1 visits each node and returns to the origin circuit Succ circuit Succ Pred where Succ is a list of length n of domain variables or integers The i th element of Succ Pred is the successor predecessor of i in the graph True if the values form a Hamiltonian circuit The following four constraints can be thought of as constraining n tasks each with a start time Sj and a duration Dj so that no tasks ever overlap The t
95. conversion between corresponding Prolog argument and Java type will take place Note The conversion declarations composed of the declarators specified below together with the method 3 term are used by the glue code generator to create the method s type signature i e a string which can uniquely identify a method within a class This means that unlike the C interface the conversion declarations for a Java method will affect the lookup of the method name in the C interface only the function name is relevant So if a method is declared as foo integer there must be a method which has the name foo and takes one argument of type int or an argument which can be automatically converted to an int a short for example Chapter 9 Mixing Java and Prolog 169 Prolog integer Java int The argument should be a number It is converted to a Java int Prolog byte Java byte The argument should be a number It is converted to a Java byte Prolog short Java short The argument should be a number It is converted to a Java short Prolog long Java long The argument should be a number It is converted to a Java long Note Since Java s long type is 64 bits wide and there is no standardized support for 64 bits integers in C the value will be truncated So this declaration is really only useful in order to indicate which method should be used For example class Bar void foo int x Ea void foo long x ue In order
96. definite clauses tells us which goals can be considered true according to a given program and is defined recursively as follows A goal is true if it is the head of some clause instance and each of the goals if any in the body of that clause instance is true where an instance of a clause or term is obtained by substituting for each of zero or more of its variables a new term for all occurrences of the variable For example if a program contains the preceding procedure for concatenate 3 then the declarative semantics tells us that concatenate a b a b is true because this goal is the head of a certain instance of the first clause for concatenate 3 namely concatenate a b a b concatenate b b and we know that the only goal in the body of this clause instance is true since it is an instance of the unit clause which is the second clause for concatenate 3 34 SICStus Prolog 2 3 Procedural Semantics Note that the declarative semantics makes no reference to the sequencing of goals within the body of a clause nor to the sequencing of clauses within a program This sequencing information is however very relevant for the procedural semantics which Prolog gives to definite clauses The procedural semantics defines exactly how the Prolog system will execute a goal and the sequencing information is the means by which the Prolog programmer directs the system to execute the program in a sensible way
97. definition of physical object are equivalent to the previous one physical object 1 volume 50 amp density 100 amp weight X self S S volume V S density D X is V D jm physical object 1 volume 50 amp density 100 weight X self volume V self density D X is VxD 32 4 Object Hierarchies Inheritance and Modules The Prolog Objects system implements a default inheritance mechanism By declaring within an object which objects are super objects the hierarchy of objects are maintained The system also maintains for each object its immediate sub objects i e immediate children Each object may also call Prolog predicates At the top of the hierarchy the proto object object provides various services for other objects If object is not used at the top of the hierarchy many services will not be available for other objects check what methods are available in object by sending the message method 1 to object 334 SICStus Prolog 32 4 1 Inheritance Immediate super objects are declared by defining the method super 2 within the object Any definition super Super is transformed to super Super 1 The objects declared by super 2 are the immediate objects from which a method is inherited if not defined within the object This implies that the inheritance mechanism is an overriding one One could possibly have a union inheritance whereby all clauses defining a method are collected from the
98. e a mapping from keys to terms that can be read or written simultaneously by parallel execution branches See Section 7 11 Blackboard Primitives page 116 Warning The blackboard predicates as well as predicates loaded via the foreign language interface can be executed even if the current work is speculative These predicates are cavalier i e a call might be executed in a parallel execution even if that call would never be reached in a sequential execution if the code contains cuts see Section 2 5 Cut page 36 or calls to raise_exception 1 This problem can be partly cured by avoiding cuts while searching for solutions or by inserting extra validity tests in the program before calling a cavalier primitive tests which would be redundant in a sequential execution Remember that the validity tests may themselves succeed out of order if they contain parallelism so they should also be written without cuts and exceptions or be explicitly sequentialized Ideally the cavalier predicates should be asynchronous rather than cavalier This means that they should suspend until they are no longer endangered by cuts or calls to raise_exception 1 but that functionality cannot be provided in the current release at least Other limitations in Muse concern certain built in predicates and the foreign language interface The limitations are mentioned when describing these functions They can be summarized as follows e During parallel execution pr
99. e r SII Meee XE 112 core statistics 2 option 4 109 cos 1 function 0 ARDEI cee ees 95 cosh 1 function ccc cece es 95 cot A dr asa aides 95 coth 1 function eo eea cece eens 95 COMUNE 4 es di eter ee LU RR 277 create mutable 2 ssseeeeeee eene 113 creep debugger command s sess 65 cumulative 4 sss 279 current atomie ito 104 current constraint 2 cece eee eee 313 current D A ooo oc ooo ooo 237 current_handler 2 0 cece cee eee 313 current host 1 0 ee 230 current input l cicer Reese nens 90 c rrent key 2 aride i iei BRIT 116 current _module 1 cece cece eese 105 current module 2 sess eene 105 CULT EOL Ina des scm tree Pa Re a 124 current output 1 esses nne 90 current predicate 2 isse 104 Current stream 3 x nea ata Ek 90 cycTioverm Tj co va tio od morada else pus Ese dus 206 D datime 12s cere rr benc 215 db buffering 2 dila eyed leid ewes eile x 238 db buffering 3 liess 238 db canonical 2 2 ceived Ce REPRE EO ERE 238 db canonical 3 meeue oR TERTE RE es 238 db close 0 sume d aam bb eR A Taf mida 237 dbichose 1 side ue poser dub P eM dud 237 db erase 1 c e eet Rd 237 db2erase 2 ic AA AA end 237 A ag dau vee resi ete gd diri 237 dbzfetch d osa E epi s 237 db_findall 2 2c cc cect eens 237 db3findall 3 4 vA ERG IX WR E RAI YER 237 Ab open A Ae N
100. 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 A 1 0 B 0 9999999999999999 C 10 0 The shortcut bypassing the use of 1 is allowed and makes sense because the interpretation 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 Section 29 9 1 1 Rationals page 269 Failing to do so is rewarded with an exception clp q 2 A 3 B C 2 C 10 0 A B TYPE ERROR _165 10 0 arg 2 expected a rational number found 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 If you use 3 1 you don t have to worry about such details Alternatively you may use the automatic expansion facility check Section 29 7 Syntactic Sugar page 265 Chapter 29 Constraint Logic Programming over Rationals or Reals 253 29 2 3 Feedback and Bindings What was covered so far was how the user populates the const
101. element in the domain of Y and vice versa This constraint uses an optimized algorithm for the special case where List is ground element 3 maintains domain consistency see Section 30 7 The Constraint System page 283 relation X MapList Y where X and Y are integers or domain variables and MapList is a list of integer ConstantRange pairs where the integer keys occur uniquely see Syntax of Indexicals page 301 True if MapList contains a pair X R and Y is in the range denoted by R Operationally the domains of X and Y are constrained so that for every element in the domain of X there is a compatible element in the domain of Y and vice versa If MapList is not ground the constraint must be wrapped in ca11 1 to postpone goal expansion until runtime An arbitrary binary constraint can be defined with relation 3 relation 3 maintains domain consistency see Section 30 7 The Constraint System page 283 278 SICStus Prolog all_different Variables where Variables is a list of domain variables or integers Each variable is constrained to take a value that is unique among the variables Operationally this is equivalent to posting an inequality constraint for each pair of variables This constraint wakes up each time a variable becomes ground pruning the domains of the other variables The implementation is incomplete i e domain elements for Vari ables for which the constraint has no solutions are not always eliminated A
102. elements of list L The goal reverse L1 L2 is true if list L2 consists of the elements of list L1 in reverse order concatenate L L concatenate X L1 L2 X L3 concatenate L1 L2 L3 member X X _ member X _ L member X L reverse L L1 reverse concatenate L L1 reverse concatenate L L reverse concatenate X L1 L2 L3 reverse concatenate Li X L2 L3 10 5 2 Family Example descendants The goal descendant X Y is true if Y is a descendant of X 180 SICStus Prolog descendant X Y offspring X Y descendant X Z offspring X Y descendant Y Z offspring abraham ishmael offspring abraham isaac offspring isaac esau offspring isaac jacob If for example the query descendant abraham X is executed Prolog s backtracking results in different descendants of Abraham being returned as successive instances of the variable X i e ishmael isaac esau jacob P4 P4 P4 Pd 10 5 3 Association List Primitives These predicates implement association list primitives They use a binary tree representation Thus the time complexity for these predicates is O Ig N where N is the number of keys These predicates also illustrate the use of compare 3 see Section 7 3 Term Compare page 97 for case analysis The goal get assoc Key Assoc Value is true when Key is identical to one of the keys in Assoc and Value unifies with the associ
103. empty heap heap size Heap Size Size is the number of elements in the heap Heap heap to list Heap List Returns the current set of Key Datum pairs in the Heap as a keysorted List is heap Heap is true when Heap is a valid heap list to heap List Heap Takes a list List of Key Datum pairs and forms them into a heap Heap Example list to heap 1 34 2 345 5 678 H H t 3 1 t 1 34 t 2 345 t t t 5 678 t t yes 200 SICStus Prolog min_of_heap Heap Key Datum Returns the Key Datum pair at the top of the heap Heap without removing it Fails if the heap is empty min_of_heap Heap Keyl Datuml Key2 Datum2 Returns the smallest Key1 Datum1 and second smallest Key2 Datum2 pairs in the Heap without deleting them It fails if the heap does not have at least two elements delete from heap OldHeap Key Datum NewHeap deletes a single Key Datum pair in OldHeap producing NewHeap This is useful if you want to e g change the priority of Datum Beware this operation needs to search the whole heap in the worst case Chapter 16 List Operations 201 16 List Operations This package defines operations on lists Lists are a very basic data structure but nevertheless certain very frequent operations are provided in this package To load the package enter the query use_module library lists append Prefix Suffix Combined Combined is the combined list of the elements in
104. if B is set to 1 e the negation of the constraint is posted if B is set to 0 e B is set to 1 if the constraint becomes entailed Chapter 30 Constraint Logic Programming over Finite Domains 275 e B is set to 0 if the constraint becomes disentailed This mechanism is known as reification Several frequently used operations can be defined in terms of reified constraints such as blocking implication Saraswat 90 and the cardinality operator Van Hentenryck amp Deville 91 to name a few A reified constraint is written Constraint lt gt B where Constraint is reifiable As an example of a constraint that uses reification consider exactly X L N which is true if X occurs exactly N times in the list L It can be defined thus exactly O 0 exactly X Y L N X Y lt gt B N M B exactly X L M 30 3 Available Constraints This section describes the classes of constraints that can be used with this solver 30 3 1 Arithmetic Constraints Expr RelOp Expr defines an arithmetic constraint The syntax for Expr and RelOp is defined by a grammar see Syntax of Arithmetic Expressions page 303 Note that the expressions are not restricted to being linear Constraints over non linear expressions however will usually yield less constraint propagation than constraints over linear expressions Arithmetic constraints can be reified as e g X in 1 2 Y in 3 5 X lt Y lt gt B B 1 X in Y
105. in conjunction with load_type source to ensure that the source file will be loaded even in the presence of an object file Consults the source file or list of files specified by File and Files Same as load_ files Files load_type source compilation_mode consult compile Files Compiles the source file or list of files specified by Files The compiled code is placed in core i e is added incrementally to the Prolog database Same as load_files Files 1oad type source compilation mode compile load Files Loads the object file or list of files specified by Files Same as load files Files 1oad type object 1 Chapter 7 Built In Predicates 75 ensure_loaded Files Compiles or loads the file or files specified by Files that have been modified after the file was last loaded or that have not yet been loaded The recommended style is to use this predicate for non module files only but if any module files are encountered their public predicates are imported Same as load_files Files if changed use module File Compiles or loads the module file specified by File if it has been modified after it was last loaded or not yet been loaded Its public predicates are imported The recommended style is to use this predicate for module files only but any non module files encountered are simply compiled or loaded Same as load_files File if changed use_module File Imports Loads the module file File l
106. inserted into the constraint store i e after all rules have been tried 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 applyl Pre defined shortcuts are 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 Chapter 31 Constraint Handling Rules 319 31 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 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 on 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
107. is 0 system Command Status Passes Command to a new default shell process for execution The status value is returned in Status tmpnam FileName Interface to the ANSI C function tmpnam 3 A unique file name is created and unified with FileName wait Pid Status Waits for the child process Pid to terminate The exit status is returned in Status The function is similar to that of the UNIX function waitpid 3 working directory OldDirectory NewDirectory OldDirectory is the current working directory and the working directory is set to NewDirectory In particular the goal working directory Dir Dir unifies Dir with the current working directory without changing anything 218 SICStus Prolog Chapter 22 Updatable Binary Trees 219 22 Updatable Binary Trees This package uses binary trees to represent arrays of N elements where N is fixed unlike library arrays To load the package enter the query use_module library trees Binary trees have the following representation t denotes the empty tree and t Label Left Right denotes the binary tree with label Label and children Left and Right gen label Index Tree Label Label labels the Index th element in the Tree Can be used to enumerate all Labels by ascending Index Use get 1abe1 3 instead if Index is instantiated get_label Index Tree Label Label labels the Index th element in the Tree list_to_tree List Tree Constructs a b
108. is connected to the server and that the tuple space initially is empty out x a 3 out x a 4 out x b 3 out x c 3 yes bagof_rd_noblock C N x C N L C _32 L a 3 a 4 b 3 c 3 N _52 yes bagof rd noblock C N x C N L C _32 L a a b cl N _48 yes Chapter 27 External Storage of Terms External Database 235 27 External Storage of Terms External Database This library handles storage and retrieval of terms on files By using indexing the store retrieve operations are efficient also for large data sets The package is loaded by the query use_module library db 27 1 Basics The idea is to get a behavior similar to assert 1 retract 1 and clause 2 but the terms are stored on files instead of in primary memory The differences compared with the internal database are e A database must be opened before any access and closed after the last access There are special predicates for this db_open and db_close e The indexing is specified when the database is created It is possible to index on other parts of the term than just the functor and first argument e Changes affect the database immediately e The database will store variables with frozen goals as ordinary variables Some commercial databases can t store non ground terms or more than one instance of a term The SICStus database can however store terms of either kind The database is kept in a se
109. ld so 1 home bob mysicstus lib sicstus37beta bin sp exe fatal libsprt37 so can t open file errno 2 Killed The cure for this is to explicitly set the runtime linker search path variable to contain the path to libsprt37 so For sh bash etc this is done by export LD LIBRARY PATH 4LD LIBRARY PATH home bob mysicstus lib and for csh tcsh etc by setenv LD_LIBRARY_PATH 1LD LIBRARY PATH home bob mysicstus lib The runtime linker search path variable is not always called LD_LIBRARY_PATH this depends on which runtime linker the system uses and how it is configured Other possible names are LD_RUN_ PATH LIBRARY PATH and SHLIB PATH The latter is mostly used under IRIX Check your system documentation or ask your system administrator for details 10 SICStus Prolog 1 1 2 Environment Variables The following environment variables can be set before starting SICStus Prolog Some of these override the default sizes of certain areas The sizes are given in bytes but may be followed by K or M meaning kilobytes or megabytes respectively SP_CTYPE SP_PATH TMPDIR Selects the appropriate character set standard The supported values are euc for EUC and iso_8859_1 for ISO 8859 1 The latter is the default This environment variable is used to determine the location of the Runtime Library It is normally not necessary to set this environment variable under UNIX it is hard coded into the start up scrip
110. list zero otherwise int SP is atomic SP term ref t Returns nonzero if the term is an atomic Prolog term zero otherwise int SP is number SP term ref t Returns nonzero if the term is a Prolog number zero otherwise 8 3 5 Unifying and Comparing Terms int SP unify SP term ref x SP term ref y Unifies two terms returning zero on failure and nonzero on success int SP compare SP term ref x SP term ref y Returns 1 if x lt y 0 if x y and 1 if x 0 y 8 3 6 Memory Allocation The usual C library memory allocation functions malloc realloc and free may not work properly in foreign code The following functions provide these services from SICStus Prolog s memory manager void SP_malloc unsigned int size Returns a properly aligned pointer to a block of at least size bytes In Muse the blocks are allocated in shared memory void SP_realloc void ptr unsigned int size Changes the size of the block referenced by ptr to size bytes and returns a pointer to the possibly moved block The contents will be unchanged up to the lesser of the new and old sizes The block referenced by ptr must have been obtained by a call to SP malloc or SP_realloc and must not have been released by a call to SP free or SP realloc In Muse the blocks are allocated in shared memory void SP free void ptr Releases the block referenced by ptr which must have been obtained by a call to SP malloc or SP_realloc and must not h
111. make stream and the deletion is done from the Prolog predicate close 1 char filename This field is set to the empty string by SP make stream May be set to a suitable string provided the string will not be overwritten until the stream is closed unsigned long mode A bit vector that contains information about the access modes supported if the stream is a TTY stream etc It is not available to the user but the TTY property can be set by the function void SP set tty SP stream s 148 SICStus Prolog int fd The I O descriptor if the stream is associated with a file socket etc Otherwise a negative number void user_handle This is the pointer to the user supplied private data for the stream In the case of SICStus Prolog predefined file streams the user_handle could be a pointer to the standard I O FILE There is no standard way to tell if a stream is user defined You have to save pointers to the streams created or check if one of the stream functions installed is user defined i e int is_my_stream SP_stream s X return s gt sclose my close 8 5 3 Hookable Standard Streams As of SICStus release 3 7 the standard I O streams input output and error are hookable i e the streams can be redefined by the user SP_UserStreamHook SP_set_user_stream_hook SP_UserStreamHook hook Sets the user stream hook to hook SP_UserStreamPostHook SP_set_user_stream_post_hook SP_UserStreamPostHook hook
112. minimize End End Ss after TI after S Ss DIDs E E gt S D after Ss Ds E 44 End of file schedule Ss End Ss 1 17 10 10 5 5 1 End 23 Chapter 30 Constraint Logic Programming over Finite Domains 301 30 11 Syntax Summary Syntax of Indexicals 302 X gt variable Constant gt integer inf sup Term Constant X min X max X card X Term Term Term Term Term Term Term Term Term Term Term Term mod Term TermSet gt Term Range TermSet dom X Term Term Range Range Range Range Mange Range Range Range Range Range Range Term Range Term Term Range SICStus Prolog domain variable Y minus infinity plus infinity suspend until assigned min of domain of X max of domain of X size of domain of X division rounded up division rounded down Term domain of X interval intersection union complement pointwise negation pointwise addition pointwise subtraction pointwise modulo pointwise addition pointwise subtraction pointwise subtraction Range mod Range Range mod Term Range Range wunionof X Range Range switch Term MapList ConstantSet integer integer ConstantRange gt ConstantSet Constant Con
113. oe Ree eae 211 R random numbers 0 000s eee e eee eee eee 213 POACIN GAN ites Sora A IR Me MATER 11 Peconsult Bice hid hed tolled det dea IRA 68 Tecursi n ball nse wie nia eel PERE or a Ee oP ROE 178 fed CUE i4 da ena ea eae OER ORIN ea Nae hae 37 reference term 2 00 or 127 reificatlont zoo pheno pass ema P piti vu ees a 275 reinitialization s sTo recre iss rpi EE eee eee 125 126 reinitialization hook functions 150 Pepeat looper cce sient O G et 93 TESOUTCE foreign at rn ore tek Se tears 128 TESTO opp oath ted chatted ve Um 17 rule computation 00 eene 35 rul grammar r2 llkele Rel rere er per e ard 76 r len search 252A nee Rd raids 35 TUI rara An e pou lee MOERS T runtime kernel o oococccoccocccorccc o 373 runtime System ic dug p ka eek dau 6 151 S Saved Stated pee n a en EE a ERE ie A 17 SAVING oie eserpecovendz ciao ta natant eon a est ude estes 17 sched ler i oet Resse Tait carina Taste 43 schedulimg ciuis epe rd gree ads 43 search Tiles c2 in M Re dete ares 35 self igh ie ative do Bane re SUUS fa 332 semantics ver e A S T EN 33 34 sending message gitara lta erp a Hindar alta aaa Ala 332 Sentences ti ie 30 sequence ESCAPE eee 106 401 sequential declaration 0 eee e eee eee 57 rancq LEE 207 shallow failure 00 000008 122 178 side etfects cei wince ciate RENAE 44 signal handling s
114. of Self descendant Object One of the descendants of Self is Object descendant Object Level Object a descendant at depth Level of Self A child of Self is at level 1 descendants Objects The list of all descendants of Self is Objects descendants Objects Level Objects is the list of descendants at depth Level of Self ancestor Object One of the ancestors of Self is Object ancestor Object Level Object is an ancestor of Self at height Level A super object of Self has level 1 ancestors Object The list of all ancestors of Self is Objects ancestors Object Level Objects is the list of ancestors at height Level of Self restart Removes all dynamic objects Note that dynamic methods added to static objects are not removed and cast Objects Message Sends the same message Message to all objects in the list Objects or cast Objects Message Sends the same message Message to one of the objects in the list Objects backtracking through the alternative objects Chapter 32 Prolog Objects 345 32 9 Expansion to Prolog Code As already mentioned object definitions are expanded to Prolog clauses much as definite clause grammars This expansion is usually transparent to the user While debugging a Prolog Objects program however the expanded representation may become exposed This section will explain in detail the source expansion so as to give the user the possibility to relate back to the so
115. of the same type and precedence It is possible to have more than one operator of the same name so long as they are of different kinds i e infix prefix or postfix An operator of any kind may be redefined by a new declaration of the same kind This applies equally to operators which are provided as standard Declarations of all the standard operators can be found elsewhere see Standard Operators page 403 For example the standard operators and are declared by op 500 yfx DD so that a btc is valid syntax and means a b c i e Chapter 2 The Prolog Language 39 The list functor is not a standard operator but if we declare it thus op 900 xfy then a b c would represent the structure eN a SN b c Contrasting this with the diagram above for a b c shows the difference between yfx operators where the tree grows to the left and xfy operators where it grows to the right The tree cannot grow at all for xfx operators it is simply illegal to combine xfx operators having equal precedences in this way The possible types for a prefix operator are fx fy and for a postfix operator they are xf yf The meaning of the types should be clear by analogy with those for infix operators As an example if not were declared as a prefix operator of type fy then not not P would be a permissible way to write not not P If the type were fx the preceding expression would not be legal although not P
116. of these predicates are subject to module name expansion so the module name does not have to be explicitly given unless multiple Prolog modules are supposed to share a single blackboard The predicates below implement atomic blackboard actions In Muse these predicates are cavalier see Section 3 5 Programming Considerations page 45 bb put Key Term A copy of Term is stored under Key Any previous term stored under the same Key is simply deleted bb get Key Term If a term is currently stored under Key a copy of it is unified with Term Otherwise bb get 2 silently fails Chapter 7 Built In Predicates 117 bb_delete Key Term If a term is currently stored under Key the term is deleted and a copy of it is unified with Term Otherwise bb_delete 2 silently fails bb_update Key OldTerm NewTerm If a term is currently stored under Key and unifies with OldTerm the term is replaced by a copy of NewTerm Otherwise bb_update 3 silently fails This predicate provides an atomic swap operation The following example illustrates how these primitives may be used to implement a maxof pred icate that finds the maximum value computed by some non deterministic goal which may execute in parallel We use a single key max Note the technique of using bb_update 3 in a repeat fail loop since other execution branches may be competing for updating the value and we only want to store a new value if it is greater than the
117. of three parts a port a goal template and a test arbitrary Prolog goal usually sharing some variables with the test part For the spy point to apply the port and goal parts must match and the test must succeed otherwise the spy point is simply disabled The following example illustrates how to define a spy point to only apply at Call ports when a test is satisfied 4 2 Call nr 0 1 2 3 4 5 6 7 8 9 1 267 1 Goal Port Cond nr L _ call length L N N 3 Spy point placed on user nr 2 4 2 Call nr 0 1 2 3 4 5 6 7 8 9 _267 7 1 32 30 Call nr 8 9 2771 s nospy this removes the spy point from the current goal if it exists and any condition for that spy point find this outputs information about where the predicate being called is defined abort causes an abort of the current execution All the execution states built so far are destroyed and you are put right back at the top level This is the same as the built in predicate abort 0 68 SICStus Prolog break calls the built in predicate break 0 thus putting you at a recursive top level with the execution so far sitting underneath you When you end the break D you will be reprompted at the port at which you broke The new execution is completely separate from the suspended one the invocation numbers will start again from 1 during the break The debugger is temporarily switched off as you call the break and will be re switched on when you finish the
118. predicates should always be declared as multifile and dynamic as this is the convention followed in the library modules Multifile declarations must precede any other declarations for the same predicate s 5 2 2 Dynamic Declarations A declaration dynamic PredSpec PredSpec where each PredSpec is a predicate spec causes the specified predicates to become dynamic which means that other predicates may inspect and modify them adding or deleting individual clauses Dynamic predicates are always stored in consulted form even if a compilation is in progress This declaration is meaningful even if the file contains no clauses for a specified predicate the effect is then to define a dynamic predicate with no clauses Chapter 5 Loading Programs 55 5 2 3 Volatile Declarations A declaration volatile PredSpec PredSpec where each PredSpec is a predicate spec causes the specified predicates to become volatile A predicate should be declared as volatile if it refers to data that cannot or should not be saved in a saved state In most cases a volatile predicate will be dynamic and it will be used to keep facts about streams or memory references When a program state is saved at run time the clauses of all volatile predicates will be left unsaved The predicate definitions will be saved though which means that the predicates will keep all properties that is volatile and maybe dynamic or multifile when the saved state is restore
119. progress and error messages The DEC 10 Prolog I O predicates manipulate streams implicitly by maintaining the notion of a current input stream and a current output stream The current input and output streams are set to the user_input and user_output initially and for every new break see Section 1 9 Nested page 16 The predicate see 1 te11 1 can be used for setting the current input output stream to newly opened streams for particular files The predicate seen 0 told 0 close the current input output stream and resets it to the standard input output stream The predicate seeing 1 telling 1 is used for retrieving the filename associated with the current input output streams The possible formats of a filename are user This filename stands for the standard input or output stream depending on context Terminal output is only guaranteed to be displayed if the output stream is explicitly flushed File where File is any atom other than user denotes a file File with an optional p1 suffix when consulting or compiling or an optional q1 suffix in load 1 located using services provided by the operating system On UNIX systems Filenames beginning with are absolute other filenames are looked up in the current working directory Alias File where File is an atom denotes an alias which must be rewritten using the user defined predicate user file search path 2 until an atomic filename is obtained Filenam
120. 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 Heads Head Head Heads Head Constraint Constraint 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 gt a callable term including conjunction and disjunction etc Body gt Goal Pragma a conjunction of terms usually referring to one or more heads identified via 2 The symbol separates the 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 d
121. s of the attribute specified by the head functor of Attribute The value s are unified with the argument s of Attribute set Attribute Sets the attribute value s of the attribute specified by the head functor of Attribute The value s are taken from the argument s of Attribute 342 SICStus Prolog 32 8 3 The Proto Object object The proto object object provides basic methods that are available to all other objects by delegation super Object Object is a parent a super object of Self Note that any other definition of super Object are translated to the universal method super 2 sub Object Object is a child a sub object of Self self Self Unifies Self with self Note this method is inlined when possible object Object One of the defined objects in the system is Object dynamic Self is a dynamic object static Self is a static object dynamic Name Arity Name Arity is a dynamic method of Self static Name Arity Name Arity is a static method of Self new Object Creates a new dynamic Object Self will be the prototype of Object Object can be a compound term an atom or a variable In the last case the method generates a unique name for Object SomeObject new NewObject Supers NewObject is created with Supers specifying the super objects prototypes Supers is a list containing super specifications A super specification is either an object identifier or a pair Object NotInheritList
122. sample query yields library clpqr examples mg clp r use_module library clpqr examples mg clp r mg P 12 0 01 B Mp 1B71 1268250301319698 xP 12 682503013196973 MpJ Without projection of the answer constraints onto the query variables we would observe the fol lowing interaction clp r mg P 12 0 01 B Mp B 12 682503013196973 _A 11 682503013196971 P d M 2 jm LM UE 2 E ta Mp B C D E F G H I J K _A 1 01 P O01 _A 1 01 P 0301 _A 2 0301 P 060401000000001 _A 101005010000001 _A 213535210701001 _A 285670562808011 _A 368527268436091 _A 3 0604009999999997 P 4 10100501 P 5 152015060099999 P 6 7 8 213535210700999 P 285670562808009 P 368527 26843609 P 0 462212541120453 _A 9 46221254112045 P 1 566834666531657 _A 10 566834666531655 P 2 3 4 5 6 152015060100001 A T 8 9 1 1 260 SICStus Prolog 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 29 5 1 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 might The predicate ordering Spec gives you some control over the variable ordering Suppose that ins
123. set into the X0 X1 space can be computed via the implicit elimination of non query variables clp q example 2 X0 X1 X0 2619277 17854273 X1 gt 851123 17854273 X0 6429953 16575801 X1 lt 12749681 16575801 X0 19130 1213083 X1 gt 795400 404361 X0 1251619 3956679 X1 gt 21101146 3956679 X0 601502 4257189 X1 gt 220850 473021 Projection is quite a powerful concept that leads to surprisingly terse executable specifications of nontrivial problems like the computation of the convex hull from a set of points in an n dimensional space Given the program from file library Cclpqr examples elimination conv_hull Points Xs lin_comb Points Lambdas Zero Xs zero Zero polytope Lambdas polytope Xs Chapter 29 Constraint Logic Programming over Rationals or Reals 263 positive_sum Xs 1 positive sum 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 o S1 S1 lin comb Ps Rest K Ks S1 S3 lin comb r Ps K S1 S2 lin comb Rest Ks S2 S3 lin comb r l EUR lin comb r P Ps K S Ss Kpsl8s11 Kps K P S lin comb r Ps K Ss Ss1 we can post the following query clp q 7 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 gt X Y gt 2 This answer is easily verified grap
124. specified with user library_directory 1 are searched for a file INDEX p1 This file is taken to contain relations between all exported predicates of the module files in the library directory and its subdirectories If an INDEX pl is not found require 1 will try to create one by loading the library package mkindex and calling make index make library index Directory see Chapter 11 The Prolog Library page 187 e The first index entry for the requested predicate will be used to determine the file to load An exception is raised if the predicate can t be located 76 SICStus Prolog e Once an INDEX pl is read it is cached internally for use in subsequent calls to require 1 e Not available in Runtime Systems 7 1 2 Term and Goal Expansion When a program is being read in SICStus Prolog provides hooks that enable the terms being read in to be source to source transformed before the usual processing of clauses or directives The hooks consist in user defined predicates that define the transformations One transformation is always available however definite clause grammars a convenient notation for expressing grammar rules See Colmerauer 75 and Pereira amp Warren 80 Definite clause grammars are an extension of the well known context free grammars A grammar rule in Prolog takes the general form head gt body meaning a possible form for head is body Both body and head are sequences of one or more
125. super hierarchy and executed in a Prolog fashion This can easily be programmed in Prolog Objects using delegation to super objects The following example shows some objects used for animal classification animal bird super animal amp Skin feather amp habitat tree amp motions fly penguin super bird amp habitat land amp motions walk motions swim amp size medium penguin motions M M walk M swim no penguin skin S S feather no The following is an example of multiple inheritance an object john is both a sportsman and a professor john 4 super sportsman amp super professor amp Fs Inheritance will give priority to the super objects by the order defined in the super 2 method Therefore in the above example John s characteristics of being a sportsman will dominate those Chapter 32 Prolog Objects 335 of being professor Other kinds of hierarchy traversal can be programmed explicitly using the delegation mechanism 32 4 2 Differential Inheritance It is possible to be selective about what is inherited by using the method super 2 Its first argument is the super object and its second is a list of the methods that will not be inherited from the super object 32 4 3 Use of Modules In Prolog Objects the visible predicates of the source module context for the object definition may be called in the body of a method The
126. 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 308 SICStus Prolog 31 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 A 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 be at most one constraint handler per module 31 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 It is recommended to include the corresponding directive at the start of your files containing handlers use module library chr 31 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 c
127. that will be interpreted as a character code N defaults to one and is interpreted as the number of times to print the character Ne NE NS Ng NG Print float The argument is a float The float and N will be passed to the C printf O function as printf Ne Arg printf NE Arg printf Nf Arg printf Ng Arg printf 4 NG Arg Chapter 7 Built In Predicates 85 Nda ND Nr NR Ng respectively If N is not supplied the action defaults to printf e Arg printf 4E Arg printf 4f Arg printf Ag Arg printf 4G Arg respectively Print decimal The argument is an integer N is interpreted as the number of digits after the decimal point If N is 0 or missing no decimal point will be printed Example format Hello id world 42 Hello 4 2 world format Hello d world 42 Hello 42 world Print decimal The argument is an integer Identical to Nd except that will separate groups of three digits to the left of the decimal point Example format Hello 1D world 12345 Hello 1 234 5 world Print radix The argument is an integer N is interpreted as a radix 2 lt N lt 36 If N is missing the radix defaults to 8 The letters a z will denote digits larger than 9 Example format Hello 2r world 15 Hello 1111 world format Hello 16r world 15 Hello
128. that you should type in one of the option codes allowed see Section 6 5 Debug Options page 65 If this particular port is unleashed then you will obviously not get this prompt since you have specified that you do not wish to interact at this point Note that calls that are compiled in line and built in predicates that are called directly from the top level are not traced There are two exceptions to the above debugger message format A message S Block p _133 indicates that the debugger has encountered a blocked goal i e one which is temporarily suspended due to insufficiently instantiated arguments see Section 2 3 Procedural page 34 No interaction takes place at this point and the debugger simply proceeds to the next goal in the execution stream The suspended goal will be eligible for execution once the blocking condition ceases to exist at which time a message S Unblock p 133 is printed Chapter 6 Debugging 65 6 5 Options Available during Debugging This section describes the particular options that are available when the system prompts you after printing out a debugging message All 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 with any blanks being completely ignored up to the end of the line RET Some options only actually require the terminator e g the creep option as we have already seen only requires
129. the Prolog compiler can be used for compiling the file 1 1 Getting Started Under UNIX SICStus Prolog is normally started from one of the shells On other platforms it is normally started by clicking on an icon However it is often convenient to run SICStus Prolog under GNU Emacs instead A GNU Emacs interface for SICStus Prolog is described later see Section 1 11 Emacs Interface page 18 From a shell SICStus Prolog is started by typing sicstus f i m Blabspath R abspathll p boot path base executable r restorefile 1 prologfile P T num F num a argument where the flags have the following meaning f Fast start Don t read any initialization file sicstusrc or sicstus ini on startup If the flag is omitted SICStus Prolog will consult this file on startup if it exists i Forced interactive Prompt for user input even if the standard input does not appear to be a terminal m Use malloc free in the memory manager s bottom layer 1 prolog file Ensure that the file prolog file is loaded on startup r saved state Restore the saved state saved state on startup This is done before any initialization file or prolog file is loaded a argument where the arguments can be retrieved from Prolog by prolog flag argv Args which will unify Args with argument represented as a list of atoms p boot path Overrides the default path for the Runtime Library from
130. the code for descendant when meeting a call to descendant in some other part of the code Exit This arrow represents a successful return from the predicate This occurs when the initial goal has been unified with one of the component clauses and any subgoals have been satisfied Control now passes out of the Exit port of the descendant box Textually we stop following the code for descendant and go back to the place we came from Redo This arrow indicates that a subsequent goal has failed and that the system is backtrack ing in an attempt to find alternatives to previous solutions Control passes through the Redo port of the descendant box An attempt will now be made to resatisfy one of the component subgoals in the body of the clause that last succeeded or if that fails to completely rematch the original goal with an alternative clause and then try to satisfy any subgoals in the body of this new clause Textually we follow the code backwards up the way we came looking for new ways of succeeding possibly dropping down on to another clause and following that if necessary Fail This arrow represents a failure of the initial goal which might occur if no clause is matched or if subgoals are never satisfied or if any solution produced is always rejected by later processing Control now passes out of the Fail port of the descendant box and the system continues to backtrack Textually we move back to the code which called this predicate and keep mov
131. the electric underscore function When enabled pressing underscore _ when the cursor is on a variable replaces the variable with the anynomous variable Defaults to nil prolog old sicstus keys flag Set to t to enable the key bindings of the old Emacs interface These bindings are not used by default since they violate GNU Emacs recommendations Defaults to nil prolog use prolog tokenizer flag Set to nil to use built in functions of Emacs for parsing the source code when indenting This is faster than the default but does not handle some of the syntax peculiarities of Prolog Defaults to t prolog parse mode What position the parsing is done from when indenting code Two possible settings beg of line and beg of clause The first is faster but may result in erroneous indentation in comments The default is beg of 1line 24 SICStus Prolog prolog imenu flag Set to t to enable a new Predicate menu which contains all predicates of the current file Choosing an entry in the menu moves the cursor to the start of that predicate Defaults to nil prolog info predicate index The info node for the SICStus predicate index This is important if the online help function is to be used by pressing C c or choosing the Prolog Help on predicate menu entry The default setting is sicstus Predicate Index prolog underscore wordchar flag Set to nil to not make underscore _ a word constituent character Defaults to t 1 11 6
132. the following suppose that list membership has been defined by loading the following clauses from a file member X X _ member X _ L member X L Notice the use of anonymous variables written _ 1 4 1 Queries The full syntax of a query is followed by a sequence of goals The top level expects queries This is signaled by the initial prompt Thus a query at top level looks like member b a b c Remember that Prolog terms must terminate with a full stop possibly followed by layout text and that therefore Prolog will not execute anything until you have typed the full stop and then RET at the end of the query If the goal s specified in a query can be satisfied and if there are no variables as in this example then the system answers yes and execution of the query terminates If variables are included in the query then the final value of each variable is displayed except for variables whose names begin with _ Thus the query Chapter 1 How to Run Prolog 13 member X a b c would be answered by X a At this point the system is waiting for input of either just a RET or else a followed by RET Simply typing RET terminates the query the system responds with yes However typing causes the system to backtrack see Section 2 3 Procedural page 34 looking for alternative solutions If no further solutions can be found it outputs no The outcom
133. there is a call to raise exception Exception then Exception is copied and the stack is unwound back to the call to on exception 3 whereupon the copy of Exception is unified with Pattern If this unification succeeds then on exception 3 calls the goal Handler in order to determine the success or failure of on exception 3 Otherwise the stack keeps unwinding looking for an earlier invocation of on exception 3 Exception may be any term Certain built in and library predicates rely on the exception mechanism so it is usually a bad idea to let Pattern be a variable matching any exception If it must be a variable the Handler should examime the exception and pass it on if it is not relevant to the current invocation 102 SICStus Prolog Instead of the above two predicates the ISO Prolog standard prescribes the following two They are functionality equivalent to the above two predicates but beware of the different argument order catch Goal Catcher Recovery on_exception Catcher Goal Recovery throw Ball raise_exception Ball In a Development System any previously uncaught exception is caught and an appropriate error message is printed before returning to the top level In recursive calls to Prolog from C uncaught exceptions are returned back to C instead The printing of these and most other messages in a Development System is handled by the predicate print message 2 The behavior of this predicate can be overridden
134. this will only generate one particular solution which is different from the situation with minimize 1 where the general solution is exhibited ordering Spec Provides a means to control one aspect of the presentation of the answer constraints see Section 29 5 1 Variable Ordering page 260 dump Target NewVars CodedAnswer Reflects the constraints on the target variables into a term where Target and NewVars are lists of variables of equal length and CodedAnswer is the term representation of the projection of constraints onto the target variables where the target variables are replaced by the corresponding variables from NewVars see Section 29 5 2 Turning Answers into Terms page 261 clp q A B lt 10 A gt 4 dump A B Vs Cs dump B Bp Cb Cb A 6 Bp A Cs _B gt 4 _C _B lt 10 Vs C B A gt 4 A B lt 10 The current version of dump 3 is incomplete with respect to nonlinear constraints It only reports nonlinear constraints that are connected to the target variables The following example has no solution From the top level s report we have a chance to deduce this fact but dump 3 currently has no means to collect global constraints qu X gt 10 sin Z gt 3 clp r q X dump X V C C _A gt 10 0 V LA clpr 3 0 sin B 0 0 X gt 10 0 252 SICStus Prolog 29 2 2 Unification Equality constraints are added to the store implicitly
135. to be able to indicate that the latter of the foo methods should be called a long declaration must be used even if the value itself will be truncated in the call Prolog float Java float The argument should be a number It is converted to a Java float Prolog double Java double The argument should be a number It is converted to a Java double Prolog term Java SPTerm The argument can be any term It is passed to Java as an object of the class SPTerm Prolog object Java SPTerm The argument should be a the Prolog representation of a Java object Unless it is the first argument in a non static method in which case is it treated as the object on which the method should be invoked it is passed to the Java method as an object of class SPTerm Prolog atom 170 SICStus Prolog Java SPTerm The argument should be an atom The Java method will be passed an object of class SPTerm Prolog boolean Java boolean The argument should be an atom in true false The Java method will receive a boolean Prolog chars Java String The argument should be a list of character codes The Java method will receive an object of class String Prolog string Java String The argument should be an atom The Java method will receive an object of class String Prolog atom Java SPTerm The argument should be an unbound variable The Java method will receive an atom of class SPTerm which can be modified The argument will be bou
136. to selectively set spy points Spy points allow you to nominate interesting predicates at which the program is to pause so that you can interact e The wide choice of control and information options available during debugging The Procedure Box model of execution is also called the Byrd Box model after its inventor Lawrence Byrd Much of the information in this chapter is also in Chapter eight of Clocksin amp Mellish 81 which is recommended as an introduction Unless otherwise stated the debugger print goals using write_term 3 with the value of the Prolog flag debugger_print_options see Section 7 6 State Info page 104 The debugger is not available in Runtime Systems and the predicates defined in this chapter are undefined see Section 8 8 Runtime Systems page 151 6 1 The Procedure Box Control Flow Model During debugging the debugger prints out a sequence of goals in various states of instantiation in order to show the state the program has reached in its execution However in order to understand what is occurring it is necessary to understand when and why the debugger prints out goals As in other programming languages key points of interest are predicate entry and return but in Prolog there is the additional complexity of backtracking One of the major confusions that novice Prolog programmers have to face is the question of what actually happens when a goal fails and the system suddenly starts backtracking The Procedure
137. which the value of the user library_directory 1 fact is derived This option is only relevant for statically linked Development Systems see Section 8 9 Development Systems page 156 as an alternative to setting the SP PATH variable see Section 1 1 2 Environment Variables page 10 The use of this flag is discouraged Use the base option instead 8 SICStus Prolog base executable Unix platforms only Override the binary used when executing SICStus from within the start script Useful for example for statically linked Development Systems see Section 8 9 Development Systems page 156 to avoid having to set environment vari ables such as SP_PATH see Section 1 1 2 Environment Variables page 10 which are set by the start script P num PT num The uninstrumented P or trace PT version of Muse is started As an option num specifies the initial number of workers used defaults to 1 See Section 3 3 1 Muse Exe Model page 43 Only available if Muse has been installed F num Only useful for the Sequent Symmetry version of Muse Its purpose is to preallocate shared memory for num workers If the F argument is not used num is assumed to be equal to the default number of workers B abspath Creates a saved state for a development system This option is not needed for normal use If abspath is given it specifies the absolute pathname for the saved state Note There must not be a space before the path or i
138. with calling tk do one event 0 1 in lengthy computations The second alternative is using the Tcl command prolog event The user program then by calling tk next event 2 3 passes control to Tcl Tk until one or more invocations of prolog event has occurred The Prolog event determines the Prolog action to take This approach has the advantage that context variables might be passed around in the event loop Chapter 35 The Gauge Profiling Tool 367 35 The Gauge Profiling Tool The Gauge library package is a graphical interface to the Sicstus built in predicates profile_ data 4 and profile_reset 1 See Section 7 15 Profiling page 121 for more information about execution profiling The interface is based on Tcl Tk see Chapter 34 TclTk page 361 Gauge loads Tcl Tk if it is not previously loaded To use the gauge package enter the query use_module library gauge view Spec Creates a graphical user interface for viewing the profile data for the predicates covered by Spec which has the same form as for spy 1 see Section 6 3 Spy Point page 62 For example the call view user _ m2 _ will bring up the graphical user interface on the predicates contained in the modules user and m2 When the display first comes up it is blank except for the control panel The graphical interface is pretty much self explanatory The on line help function gives all necessary information 368 SICStus Prolog Chapter 36 I O on
139. with the first argument unbound and the second and third arguments bound to an atom and an integer respectively int SP put list SP term ref t Assigns to t a Prolog list whose head and tail are both unbound variables int SP cons functor SP term ref t unsigned long name int arity SP term ref arg od Assigns to t a Prolog compound term whose arguments are the values of arg If arity is 0 assigns the Prolog atom whose canonical representation is name to t This is similar to calling 2 with the first argument unbound and the second argument bound int SP cons list SP term ref t SP term ref head SP term ref tail Assigns to t a Prolog list whose head and tail are the values of head and tail 8 3 3 Accessing Prolog Terms These functions will take an SP term ref and convert it to C data They return zero if the conversion fails and a nonzero value otherwise and except the last one store the C data in output arguments int SP get integer SP term ref t long 1 Assigns to 1 the C long corresponding to a Prolog number The value must fit in 1 for the operation to succeed int SP get float SP term ref t double d Assigns to d the C double corresponding to a Prolog number int SP get atom SP term ref t unsigned long a Assigns to a the canonical representation of a Prolog atom int SP get string SP term ref t char name Assigns to name a pointer to the string that is the name of a Prolog atom This s
140. with weight W is represented as the term U V W U and V must be distinct A vertex can be any term Two vertices are distinct iff they are not identical A path from u to v is represented as a list of vertices beginning with u and ending with v A vertex cannot appear twice in a path A path is maximal in a graph if it cannot be extended A tree is a tree shaped directed graph all vertices have a single predecessor except the root node which has none A strongly connected component of a graph is a maximal set of vertices where each vertex has a path in the graph to every other vertex Sets are represented as ordered lists see Chapter 18 Ordsets page 207 To load the package enter the query use_module library wgraphs The following predicates are defined for directed graphs wgraph_to_ugraph WeightedGraph Graph Graph has the same vertices and edges as WeightedGraph except the edges of Graph are unweighted ugraph_to_wgraph Graph WeightedGraph WeightedGraph has the same vertices and edges as Graph except the edges of Weight edGraph all have weight 1 vertices_edges_to_wgraph Vertices Edges WeightedGraph Vertices is a list of vertices Edges is a list of edges and WeightedGraph is a graph built from Vertices and Edges Vertices and Edges may be in any order The vertices mentioned in Edges do not have to occur explicitly in Vertices Vertices may be used to specify vertices that are not connected
141. yes Location distributor Possible Fault Worn distributor brushes 358 SICStus Prolog Chapter 33 Generalized Horn Clause Language 359 33 Generalized Horn Clause Language GCLA is a logic programming language specification tool that is based on a generalization of Prolog This generalization is unusual in that it takes a quite different view of the meaning of a logic program a definitional view rather than the traditional logical view GCLA has a number of noteworthy properties for instance the possibility to do hypothetical reasoning and non monotonic reasoning This makes implementation of reasoning in knowledge based systems more direct in GCLA than in many other formalisms GCLA is also general enough to incorporate functional programming as a special case A GCLA program is partitioned into two parts a declarative part and a control part that specifies the inference rules For an introduction to GCLA and its properties see Kreuger 91 For method ology and programming techniques see Aronsson 91 Further reading can be found in Aronsson 93 and in Falkman amp Torgersson 94 The GCLA package is documented in its own User s Manual located in library gcla doc gcla tex also available as technical report SICS T91 21A To load the package enter the query use module library gcla gcla 360 SICStus Prolog Chapter 34 Tcl Tk Interface 361 34 Tcl Tk Interface The tcltk library package
142. 0 0 0 cece eee eee 137 8 8 8 Accessing Prolog Terms 0 eee eee ee eee 138 8 3 4 Testing Prolog Terms eeee eese 139 8 3 5 Unifying and Comparing Terms 140 8 3 6 Memory Allocation seeeee I 140 8 4 Calling Prolog from C 2 ee cece eee ees 141 8 4 1 Finding One Solution of a Call o o o 141 8 4 2 Finding Multiple Solutions of a Call 141 8 4 3 Calling Prolog Asynchronously 0oooooooooo o o 142 8 4 4 Exception Handling in C 2 eee eee 144 8 5 SICStus Streams oe ee Gah ees etudes 144 8 5 1 Prolog Streams i ioc ra 145 8 5 2 Defining a New Stream 0 cece eee eee 146 8 5 2 1 Low Level I O Functions 146 8 5 2 2 Installing a New Stream 147 8 5 2 3 Internal Representation suus 147 8 5 8 Hookable Standard Streams 000 ee eee 148 8 5 3 1 Writing User stream Hooks 148 8 5 3 2 Writing User stream Post hooks 149 8 5 3 8 User stream Hook Example 149 8 6 Muse Support Functions 000 c cece cece ete nes 150 SI HOOKS wate ak up REPE CU ee Peet Gas 150 8 8 Runtime Systems Merrill EA hie ed eee 151 8 8 1 Initializing the Prolog Engine o0 oooocoooooo 151 8 8 2 Loading Prolog Code 0 0 eee eee ee 153 8 8 8 Creating the Executable 0 0c eee eee ee 1
143. 00 0 e eee eee 101 7 6 Information about the State of the Program 104 Tal Meta Topic 2 oerte ERR seat E a ia ect i m doe 110 7 8 Modification of Terms 0 cece eect e 113 7 9 Modification of the Program 0 113 7 10 Internal Database seeeeeeeee III 115 7 11 Blackboard Primitives 00 0 ccc cece enn 116 12 Al Solutions 22 1 cosi x terre e Ht Berar eee RE bode 117 LS Gorou tining erer A A A 119 GAA Debugging ici a iaa ein 120 7 15 Execution Profiling 0000s 121 GAG MUSE teeta ee A Rey heh ae Pied eee eens 123 7 17 Miscellaneous 0 eee cee ence eet e hh 124 8 Mixing C and Prolog usuus 127 Bly Notes ze e eon ed eee oie be RU PME iE 127 8 2 Calling C from Prolog sseeseeeeeee ee 128 8 2 1 Foreign Resource and Conversion Declarations 128 8 2 2 Static and Dynamic linking 04 129 8 2 3 Conversion Declarations 0 0c eee eee ee 129 8 2 4 Conversions between Prolog Arguments and C Types 130 8 2 5 Interface Predicates ccc e eee eee eee nee 133 8 2 6 Init and Deinit Functions oo o ooo o o 134 ii iv SICStus Prolog 8 2 7 Creating the Linked Foreign Resource 135 8 3 Support Functions 0 0 eee ehh 135 8 3 1 Creating and Manipulating SP term refs 136 8 3 2 Creating Prolog Terms 0
144. 0000000000 Y 2629990810403002651095959155503002285441272170673105334466808931 6863103901346024240326549035084528682487048064823380723787110941 6809235187356318780972302796570251102928552003708556939314795678 1978390674393498540663747334079841518303636625888963910391440709 0887345797303470959207883316838346973393937778363411195624313553 8835644822353659840936818391050630360633734935381528275392050975 7271468992840907541350345459011192466892177866882264242860412188 0652112744642450404625763019639086944558899249788084559753723892 16431889914449453607 2689953202354296957 2584363761073528841147012 2634218045463494055807073778490814692996517359952229262198396182 1838930043528583109973872348193806830382584040536394640895148751 0766256738740729894909630785260101721285704616818889741995949666 6303289703199393801976334974240815397920213059799071915067856758 6716458821062645562512745336709063396510021681900076680696945309 3660590933279867736747926648678738515702777431353845466199680991 73361873421152165477774911660108200059 The decimal expansion itself looks like this clp q e 1000 E 2 7182818284 6277240766 8174135966 8298807531 7614606680 5517027618 7093287091 4637721112 9316368892 6680331825 3012381970 7825098194 5988885193 4841984443 3043699418 7683964243 1718986106 5904523536 3035354759 2904357290 9525101901 8226480016 3860626133 2744374704 5238978442 3009879312 2886939849 6841614039 5581530175 4580727386 6346324
145. 1 5 Y in 2 8 T in 3 13 yes Thus when an FD predicate is called the clause is activated 294 SICStus Prolog The definition of a user constraint has to specify what domain constraints should be added to the constraint store when the constraint is posted Therefore the FD predicate contains a set of indexicals each representing a domain constraint to be added to the constraint store The actual domain constraint depends on the constraint store itself For example the third indexical in the above FD predicate prescribes the domain constraint T 3 13 if the store contains X 1 5 Y 2 8 As the domain of some variables gets narrower the indexical may enforce a new stricter constraint on some other variables Therefore such an indexical called a propagating indexical can be viewed as an agent reacting to the changes in the store by enforcing further changes in the store In general there are three stages in the lifetime of a propagating indexical When it is posted it may not be evaluated immediately e g has to wait until some variables are ground before being able to modify the store Until the preconditions for the evaluation are satisfied the agent does not enforce any constraints When the indexical becomes evaluable the resulting domain constraint is added to the store The agent then waits and reacts to changes in the domains of variables occurring in the indexical by re evaluating it and adding the ne
146. 1 N where each possible edge is included with probability P The following predicates are defined for undirected graphs only min_tree Graph Tree Cost Tree is a spanning tree of Graph with cost Cost if it exists clique Graph K Clique Clique is a maximal clique complete subgraph of N vertices of Graph where N gt K N is not necessarily maximal independent set Graph K Set Set is a maximal independent unconnected set of N vertices of Graph where N gt K N is not necessarily maximal coloring Graph K Coloring colouring Graph K Coloring Coloring is a mapping from vertices to colors 1 N of Graph such that all edges have distinct end colors where N lt K The mapping is represented as an ordered list of Vertex Color pairs N is not necessarily minimal 224 SICStus Prolog Chapter 24 Weighted Graph Operations 225 24 Weighted Graph Operations A weighted directed graph wgraph is represented as a list of vertex edgelist pairs where the pairs are in standard order as produced by keysort with unique keys the edgelist is a list of neighbor weight pair also in standard order as produced by keysort with unique keys every weight is a nonnegative integer every neighbor appears as a vertex even if it has no neighbors itself and no vertex is a neighbor to itself An undirected graph is represented as a directed graph where for each edge U V there is a symmetric edge V U An edge U V
147. 1 L L1 B gt H HO 0 H2 H H1 placed_square B H2 L L1 placed_square B B VIL XIL 1 X V B placed_square B HIL X Y L 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 Chapter 29 Constraint Logic Programming over Rationals or Reals 265 clp q use module library clpqr examples squares clp q filled rectangle A Squares k 4 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 29 7 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 tha
148. 2 floating division sse 94 2 integer division sse 94 IN 2 bitwise conjunction esses se 94 409 f comand idad b e 13 su RN e katse Sod Ret ett Ut ta e det 31 ALIAS doses a A a dte are tU d eta T m ra 100 1 message sending sss 332 2 message Sending ooooocococcccocccoco 332 gt 25 disjunctyom i eei penes NR ra 99 2 unification pr lao 124 2601 2 uni esl wv b a uie vti 111 72 2 2 arithmetic equal 0 0005 96 72 7 2 boolean equal s sss sssss 241 2 equality of terms sess 97 2 arithmetic not equal 0 96 2 boolean not equal 241 lt 2 arithmetic less or equal 96 lt 2 boolean less or equal 241 PE fils QUERY obre era Tor Gi ever c2teivu GUU vov DO Ce 12 2 2 terms identical or cannot unify 98 705 c ns lt i xii eem br erbe MENFE MATS 74 Q lt 2 term less or equal ssus 98 0 2 term greater than 0000 98 gt 2 term greater or equal 98 lt 2 term less than esee 98 DIAlganiskircvune npr eden ive ev PEERS 248 1 boolean not ce e 241 4 t i identity ore d eia iaae i E Eus 94 HPD additionner n A e E AA ES 94 EJZ DOOM OAD Toron erare heere re a Palit a 241 410 gt gt 2 arithmetic greater than
149. 3 1 Muse Exe Model page 43 1 11 Emacs Interface This section explains how to use the GNU Emacs interface for SICStus Prolog and how to customize your GNU Emacs environment for it The advantages of using SICStus in the Emacs environment are source linked debugging auto indentation syntax highlighting help on predefined predicates requires the SICStus info files to be installed loading code from inside Emacs auto fill mode and more The mode was developed for GNU Emacs 19 34 but it works well for versions 19 31 through 20 2 Earlier versions may not be able to provide syntax highlighting The mode has also been reported to work with XEmacs version 19 and 20 but it will probably not work with GNU Emacs 18 or earlier The Emacs interface is not part of SICStus Prolog proper but is included in the distribution for convenience It was written by Emil Astr m and Milan Zamazal based on an earlier version of the mode written by Masanobu Umeda Contributions has also been made by Johan Andersson Peter Olin Mats Carlsson Johan Bevemyr Stefan Andersson and Per Danielsson all at SICS and Henrik B kman at Uppsala University Sweden Some ideas and also a few lines of code have been borrowed with permission from Oz el by Ralf Scheidhauer and Michael Mehl the Emacs major mode for the Oz programming language More ideas and code have been taken from the SICStus debugger mode by Per Mildner 1 11 1 Customizing Emacs Assuming the
150. 4 if X SICStus Prolog true the default to always load or changed to load only if the file has not yet been loaded or if it has been modified since it was last loaded A non module file is not considered to have been previously loaded if it was loaded into a different module The file user is never considered to have been previously loaded when When always the default to always load or compile time to load only if the goal is not in the scope of another load_files 1 2 goal loading object code The latter is intended for use when the file only defines predicates that are needed for proper term or goal expansion during compilation of other files load type LoadType source to load source code only object to load object code only or latest the default to load source or object code whichever is newest If the file is user source is forced imports Imports all the default to import all exported predicates if the file is a module file or a list of predicates to import compilation mode Mode consult Files reconsult Files File Files compile to translate into compiled code consult to translate into static interpreted code or assert all to translate into dynamic interpreted code The default is the compilation mode of any ancestor load files 1 2 goal or compile otherwise Note that Mode has no effect when an object file is loaded and that it is recommended to use assert a11
151. 496 4914631409 7814059271 8739696552 print_decimal E 1000 0287471352 4571382178 0334295260 1573834187 8477411853 1384583000 7230696977 5056953696 7736178215 6465105820 7019837679 6717361332 6738589422 8487560233 3431738143 4563549061 1267154688 6624977572 5251664274 5956307381 9307021540 7423454424 7520449338 2093101416 7707854499 4249992295 9392398294 3206832823 0698112509 8792284998 6248270419 6405462531 3031072085 9570350354 4709369995 2746639193 3232862794 8914993488 3710753907 2656029760 9283681902 6996794686 7635148220 8879332036 7646480429 9618188159 9208680582 7862320900 5209618369 1038375051 9574966967 2003059921 3490763233 4167509244 7744992069 6737113200 5515108657 4454905987 8269895193 2509443117 5311802328 3041690351 5749279610 2160990235 0888707016 0115747704 Chapter 29 Constraint Logic Programming over Rationals or Reals 259 29 5 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 familiar mortgage relation from file mg P T I B MP 1 Teu B MP P 1 I mg P T I B MP 1 ES P1 P gt 1 I MP Ti T 1 mg P1 T1 I B MP A
152. 5 The predicates for searching for solution are documented in Section 30 4 Enumeration Predicates page 280 The predicates for getting execution statistics are documented in Section 30 5 Statistics Predicates page 282 A few example programs are given in Section 30 10 Example Programs page 298 Finally Section 30 11 Syntax Summary page 301 contains syntax rules for all expressions The following sections discuss advanced features and are probably only relevant to experienced users How to control the amount of information presented in answers to queries is explained in Section 30 6 Answer Constraints page 283 The solver s execution mechanism and primitives are described in Section 30 7 The Constraint System page 283 How to add new global constraints via a programming interface is described in Section 30 8 Defining Global Constraints page 285 How to define new primitive constraints with indexicals is described in Section 30 9 Defining Primitive Constraints page 290 Referencing this Software When referring to this implementation of clp FD in publications please use the following reference Carlsson M Ottosson G Carlson B An Open Ended Finite Domain Constraint Solver Proc Programming Languages Implementations Logics and Programs 1997 272 SICStus Prolog Acknowledgments The first version of this solver was written as part of Key Hyckenberg s MSc thesis in 1995 The code was later rewritten by Mats
153. 5 tk do one event 0 or ETE a enhn 365 tk_do_one_event 1 00 0 cee eee eee ee 365 tk_dont_wait tk_do_one_event 1 option 365 tk file events tk do one event 1 option 365 tk idle events tk do one event 1 option 365 tkmain loop 0 use reped tiere ide 366 tk main window 1 0 cece eee eee 365 tk_make_window_exist 1 000 365 TEENS 26s ace vue SN O 364 tkinextevent 2 4 vci pu GA pesce vu ds 366 tk nert eventy goei i oW UON bred 366 tk num main windows 1 sse 365 tk timer events tk do one event 1 option 365 tk window events tk do one event 1 option 365 tk x events tk do one event 1 option 365 TMPDIR environment sess 10 124 tmpnam 4 i Lil ine oe IR yx Eier eb 217 SICStus Prolog told O c unm nevibeddicbweteg nidadedahares dee 93 tOp SOEt 2 isi tise fae bern E EE EEEE 222 226 toplevel_print_options prolog flag 107 trace Diva srt at E tha Animale aia 61 121 trail statistics 2 option sss 109 TRAILSTKSIZE environment sess 10 transitive closure 2 sssss 222 226 transpose 2 2 io ererie Greer Merete eds 222 226 tree siz0 2 dati uec restitit M orte ide 219 tree to lj8t 2 5 M IP LUI Dee PER 219 DUO Oia eit Dena te a tal tp tite 100 truncate 1 function 0 ccc eee o 95 ttyflush O0 i nnt w auras AB net Mti ndtv 88 EJES da Mein eis ee p
154. 54 8 8 4 Running the Executable oooooocoooooo 155 8 9 Development Systems sseseeeee en 156 8 10 Examples src rod daa Padang dense Lewin Lg 156 8 10 1 Train Example connections 0 ooooccooooccoooo 157 8 10 2 I O on Lists of Character Codes 04 160 8 10 3 Exceptions from C 00 eee eee 162 8 10 4 Stream Example esses 164 9 Mixing Java and Prolog 167 9 1 Prerequisttes cte orate RC ra Pe SUR n e Ee RR ARR 167 9 2 Calling Java from Prolog 0 eee eee eee 167 9 2 1 Static and Dynamic Linking 00 168 9 2 2 Declarating Java methodS oo0ooooooooooomoo 168 9 3 Conversions between Prolog Arguments and Java Types 168 9 3 1 Calling Java from Prolog An Example 172 9 4 Calling Prolog from Java cece cece eee eee 173 9 5 Jasper Package Class Reference 000 cece cece esee 175 9 6 Exception Handling 0 0 ee eee 176 A A A lateat RETE 176 10 Programming Tips and Examples 177 10 1 Programming Guidelines 0 00 177 10 2 Indexing i v toasted tI CV RT DERI ore P WRSAG AR 178 10 3 Last Call Optimization ssseeeeeere e 178 10 4 If Then Else Compilation 0 0 0 eI 178 10 5 Programming Examples sesseeeee eese 179 10 5 1 Simple List Processing 02 eee cece eee eee 179 10 5 2 Family Exa
155. 68 X0 48 X1 35 X2 468 X3 35 X4 lt 85 90 XO 460 X1 76 X2 53 X3 24x X4 lt 68 95 XO 10 X1 64 X2 76 X3 24x X4 lt 33 443 X0 22 X1 67 X2 68 X3 92x X4 lt 97 439 X0 7x X1 62 X2 54 X3 26 X4 lt 27 448 X0 13 X1 7x X2 61 X3 59x X4 lt 2 449 X0 23 X1 31 X2 76 X3 27 X4 lt 3 5O XO 58 X1 1 X2 57 X3 20x X4 lt 6 262 SICStus Prolog 13 X0 63 X1 81x X2 3 X3 70x X4 lt 64 20 XO 67 X1 23x X2 41 X3 66x X4 lt 52 81 X0 44 X1 19 X2 22 X3 73x X4 lt 17 43 X0 Q xX1 14 X2 2T X3 40 X4 lt 39 16 XO 83 X1 89 X2 25x X3 55x 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 T93 XO0 T3 X1 91 X2 1 X3 23x X4 lt 87 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 gt 5 4 X0 73 93 X1 91 93 X2 1 93 X3 23 93 X4 lt 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
156. 78 information Source 0 ee eee eee 19 108 inheritance 0 0 0 eee ee eee 327 333 334 inheritance by overriding esses 327 inheritance differential 0 02 335 inheritance multiple 2000 334 IR Db zac it Pero E p MA RIEN o RI 71 input stream current 0 0 cece eee eee eee 72 instance variables poesie nrerin in 0000 e eee eee ee 351 Instances onde Baka tidak ah acai alee ate ket Saeko 341 instances implementation 0 346 Id eee ai eee EEERENMES 27 interface EMACS pa eee eee eee 18 interface foreign language ooooooo 127 128 interoperability oooococccocccconccoccc 127 interrupt handling 0 ccc cee eee eee 142 interrupt stream 0 cee cee eee 92 interval consistent 0 0 c cee eee ee eee 284 interval disentailed 0 00 02 eee ee eee 284 interval entailed 00 e cece eee eee ee 284 K kernel development 0 0 eee eee 373 kernel runtime 00 2 ccc eee eee eee 373 keyboard oie Rp ote ih oa eed ae eee aes 5 425 L last Call ii eae tenets te eae dead 178 layottterm oes 21 dae bot RICE eee as 81 ibrat yoe 404 e heated eee UR 187 Lidia arenes Het s 231 lin s end o eui SD Mee Bhd ES eis 92 linked foreign resource ooooooooocoocommmo 128 135 linking dynamic 0 00 e
157. 99 he p to list 2 vies no er E EH A 199 help debugger command sss 68 A uenis amer RE numa te ati 126 hostil lie pagia une bte bebes b bebes 216 host name 1 cessum eese peor eg cpi Vedi 216 hostname address 2 sse 230 413 O 100 Xn TA uc ate tst o tt eer ttm MIO 233 typ 233 276 An NS Leas 3 2 ots oo cise hes gee oo pp ene t 233 inset 2 oc net eet eal alata BN Wy Me aR silat BS UR 276 TACO ii id scere sm oam ait T 100 independent set 3 sse 223 indomain 4d eibi e dst ea les 280 inf O infinity L1 QI E eeu PP EM Eee 96 ANE Des cr sg ct aes fu oa Pr Pa DP cma S ges 250 initialization O sese eee 126 inmitialization 1 0 0 0 ccc eect tee 126 insert constraint 2 cece cece eens 313 insert_constraint 3 00 cece eee eee eee 313 instance 2 i bd eEMPaes etd th ive 115 instantiation error 2 error class 103 integer MS ARAB ek 110 integer 1 coerciloni sete a 94 VS DA sa tent E t eu e tes dau 96 istarray lowers Di teeta pU Dey D Ug dtt QUA 189 is assot Lia ies ees ieee 191 IS fdset 1i nen a ils bleibe haan 287 ls heap l c cei esent Erde tee fed ep Rej 199 1s Iist 1l 5 da pide aie 201 is m table lir 2 2 EE LEA EE 110 113 is ordset 1i Lc e ARM ER Penn 207 is que eAl wt aie E qe teet T 211 K keySOort 2 c xsn n EEN 98 E A mir ed RE ex oh ER REP 216 L lTabeling lo i e 6d bL bete HU Meade 242 labeling 2 esae rh a 280 FaSt A
158. ASEO Bei haces nina hee me ulerpi retra d ales 192 aprte ii gie oe ance iit trek td 219 max 2 maximum value ccc cece eee eens 95 MALLAS BEA EPOR ER 191 max list 2 bu Week REF REM adoos Hard de 201 Max path 5 iiie cesa eave ree eel 222 226 max workers muse_flag option 123 Maximizar Pin wae ge p Efe 250 maximize 2 ii eves wei EPA TEL RENE DANS 280 member Zi it eee QM EP eee EN EA 201 memberchk 2 erii IRE EE rh aed 201 memory statistics 2 option 109 meta predicate 1 declaration 50 56 method 3 Java method identifier 168 method expansion 3 sene 329 min 2 minimum value ssss esses 95 min assoc Irre is der esami qe ERR E ep TRUE 191 mindist 2 ucios yeh 4 y vata eek de weal hie dee 202 nin of heap 3 c iE eae ee ee 200 min f heap 5 saiti nies ARA A 200 Minipath enu ebia hina Rete 222 226 iin paths 3 i Rer ended Meee E ben 222 226 mi notr e 3 osas eds eps DIU DUC 223 227 minimiza rn EE 250 minimize 2 2 MIS AR NR RS 280 o 2 sarin nets due irc ite FI eu Fue n seien 216 mod 2 integer remainder ss sess 94 SICStus Prolog mode 1 declaration cece eee eee ee ee 56 module 1 a cecesekre O UR Rape CER CRAT 105 module 2 declaration sss 48 56 module 3 declaration ssse 48 56 msb 1 most significant bit sss 95 multifile 1 declara
159. Ca b L For convenience a further notational variant is allowed for lists of integers which correspond to character codes Lists written in this notation are called strings E g SICStus which represents exactly the same list as 83 73 67 83 116 117 115 As for quoted atoms if a double quote character is included in the sequence it must be written twice e g can t Backslashes in the sequence denote escape sequences see Escape Sequences page 401 2 1 2 Programs A fundamental unit of a logic program is the goal or procedure call e g gives tom apple teacher reverse 1 2 3 L X Y A goal is merely a special kind of term distinguished only by the context in which it appears in the program The principal functor of a goal identifies what predicate the goal is for It corresponds roughly to a verb in natural language or to a procedure name in a conventional programming language A logic program consists simply of a sequence of statements called sentences which are analogous to sentences of natural language A sentence comprises a head and a body The head either consists of a single goal or is empty The body consists of a sequence of zero or more goals i e it too may be empty If the head is not empty the sentence is called a clause Chapter 2 The Prolog Language 31 If the body of a clause is empty the clause is called a unit clause and is written in the form P where P is the head goal We interpret th
160. Carlsson with contributions from Greger Ottosson at the Com puting Science Department Uppsala University Peter Szeredi contributed material for this manual chapter The development of this software was supported by the Swedish National Board for Technical and Industrial Development NUTEK under the auspices of Advanced Software Technology ASTEC Center of Competence at Uppsala University We include a collection of examples some of which have been distributed with the INRIA imple mentation of clp FD Diaz amp Codognet 93 30 2 Solver Interface The solver is available as a library module and can be loaded with a query use_module library clpfd The solver contains predicates for checking the consistency and entailment of finite domain con straints as well as solving for solution values for your problem variables In the context of this constraint solver a finite domain is a subset of the integers and a finite domain constraint denotes a relation over one or more finite domains All domain variables i e variables that occur as arguments to finite domain constraints get associated with a finite domain either explicitly declared by the program or implicitly imposed by the constraint solver Temporarily the domain of a variable may actually be infinite if it does not have a finite lower or upper bound The domain of all variables gets narrower and narrower as more constraints are added If a domain becomes empty the accum
161. Consider for example a function which returns the square root of its argument after checking that the argument is valid If the argument is invalid the function should raise an exception instead math c include lt math h gt include lt stdio h gt include lt sicstus sicstus h gt double sqrt check d double d if d lt 0 0 build a domain_error 4 exception term SP_term_ref culprit SP_new_term_ref SP_term_ref argno SP_new_term_ref SP term ref expdomain SP_new_term_ref SP term ref ti SP new term ref SP put float culprit d SP put integer argno 1 SP put string expdomain gt 0 0 SP cons functor ti SP atom from string sqrt 1 culprit SP cons functor ti SP atom from string domain error 4 ti argno expdomain culprit SP raise exception ti raise the exception return 0 0 return sqrt d The Prolog interface to this function is defined in a file math pl The function uses the sqrt Q library function and so the math library 1m has to be included math pl foreign_resource math sqrt foreign sqrt_check c sqrt float float Chapter 8 Mixing C and Prolog load foreign resource math A linked foreign resource is created splfr math math pl c math c 1 lm A simple session using this function could be sicstus SICStus 3 5 Sat Feb 24 00 35 37 MET 1996 math consulting home san pl math
162. Enable or disable warning messages when a clause containing variables not beginning with _ occurring once only is compiled or consulted Initially on Corresponds to the predicate unknown 2 see Section 7 14 Debug Pred page 120 trace Causes calls to undefined predicates to be reported and the de bugger to be entered at the earliest opportunity This setting is not possible in Runtime Systems Chapter 7 Built In Predicates 107 fail Causes calls to such predicates to fail error Causes calls to such predicates to raise an exception the de fault See Section 7 5 Exception page 101 syntax_errors Controls what action is taken upon syntax errors in read 1 2 dec10 The syntax error is reported and the read is repeated error An exception is raised See Section 7 5 Exception page 101 the default fail The syntax error is reported and the read fails quiet The read quietly fails system_type A read only flag The value is development in Development Systems and runtime in Runtime Systems typein_module Permitted values are atoms Controls the current type in module see Sec tion 4 2 Module Spec page 48 Corresponds to the predicate module 1 user_input Permitted values are any stream opened for reading Controls which stream is referenced by user_input and SP_stdin It is initially set to a stream connected to UNIX stdin user_output Permitted values are any stream opened for writing Controls which st
163. GKEEPSIZE is returned to the OS the rest will be kept Chapter 1 How to Run Prolog 11 Send bug reports to lt sicstus support sics se gt Bugs tend actually to be fixed if they can be isolated so it is in your interest to report them in such a way that they can be easily reproduced The mailing list lt sicstus users sics se gt is a mailing list for communication among users and implementors To un subscribe write to lt sicstus users request sics se gt 1 2 Reading in Programs A program is made up of a sequence of clauses possibly interspersed with directives to the system The clauses of a predicate do not have to be immediately consecutive but remember that their relative order may be important see Section 2 3 Procedural page 34 To input a program from a file file just type the filename inside list brackets followed by and RET thus file This instructs the interpreter to read in consult the program Note that it may be necessary to surround the whole file specification file with single quotes to make it a legal Prolog atom e g myfile pl usr prolog somefile The specified file is then read in Clauses in the file are stored so that they can later be interpreted while any directives are obeyed as they are encountered When the end of the file is found the interpreter displays on the standard error stream the time spent for read in This indicates the completion of the directiv
164. GNU Emacs interface for SICStus Prolog has been installed inserting the following lines in your emacs or _emacs in case of Windows DOS will make Emacs use this mode automatically when editing files with a p1 extension Chapter 1 How to Run Prolog 19 setq load path cons usr local lib sicstus37 load path q P autoload run prolog prolog Start a Prolog sub process t P g P 8 g autoload prolog mode prolog Major mode for editing Prolog programs t setq prolog use sicstus sd t setq auto mode alist cons pl prolog mode auto mode alist where the path in the first line is the file system path to prolog el the Emacs interface and pltrace el the process output filter for source linked debugging For example site lisp means that the file is in the user s home directory under site lisp MSDOS paths can be written like C Program Files emacs 19 34 site lisp The last line above makes sure that files ending with p1 are assumed to be Prolog files and not Perl which is the default Emacs setting If this is undesirable remove that line It is then necessary for the user to manually switch to prolog mode by typing M x prolog mode after opening a prolog file If the shell command sicstus is not available in the default path then it is necessary to set the value of the environment variable EPROLOG to a shell command to invoke SICStus Prolog This is an example for C
165. Hook void ptr unsigned int size void SP_set_memalloc_hooks int usage SP AllocHook init_alloc_hook SP AllocHook xalloc hook SP ReAllocHook realloc hook SP FreeHook free hook The effect of SP set memalloc hooks is controlled by the value of usage which should be one of MM USE MALLOC The bottom layer will be based on malloc O free O The other arguments are ignored Same as the m option in Development Systems see Section 1 1 Start page 7 MM USE SBRK The bottom layer will be based on sbrk The default for UNIX not available for Windows The other arguments are ignored MM USE SPARSE The bottom layer will be based on VirtualAlloc O VirtualFree The default for Windows not available for UNIX The other arguments are ignored MM USE OTHER The bottom layer will be based on the other arguments Their meaning is explained below In the latter case the other arguments should be functions as specified below alloc hook must allocate and return a pointer to a piece of memory that has at least size bytes aligned at align in it align is guaranteed to be a power of 2 The actual size of the piece of memory should be returned in actual_sizep Should return NULL if it cannot allocate any more memory Chapter 8 Mixing C and Prolog 153 init_alloc_hook is a special case of alloc_hook It will be called initially whereas alloc_hook will be called subsequently It can do whatever initializatio
166. JNI can be found at http java sun com products jdk 1 1 docs guide jni index html e The ACM student magazine Crossroads has published an article on the JNI available online at http www1 acm org 82 crossroads xrds4 2 jni html Chapter 10 Programming Tips and Examples 177 10 Programming Tips and Examples This chapter describes how to write clean programs that will execute efficiently To some extent writing efficient code in any language requires basic knowledge of its compiler and we will mention some important properties of the SICStus Prolog compiler A number of simple examples of Prolog programming are also given 10 1 Programming Guidelines A lot of clarity and efficiency is gained by sticking to a few basic rules This list is necessarily very incomplete The reader is referred to textbooks such as O Keefe 90 for a thorough exposition of the elements of Prolog programming style and techniques e Don t write code in the first place if there is a library predicate that will do the job e Write clauses representing base case before clauses representing recursive cases e Input arguments before output arguments in clause heads and goals e Use pure data structures instead of data base changes e Use cuts sparingly and only at proper places see Section 2 5 Cut page 36 A cut should be placed at the exact point that it is known that the current choice is the correct one no sooner no later e Make cuts as local i
167. Key Term Delete from the blackboard Term stored under Key bb_get Key Term Get from the blackboard Term stored under Key bb put Key Term Store the term Term under Key on the blackboard bb update Key Old Term New Term Replace the term OldTerm by the term New Term under Key on the blackboard break Invokes a recursive top level not available in Runtime Systems C 781 Terminal 252 Grammar rules S1 is connected by the terminal Terminal to 5S2 call Term Module Term Executes the procedure call Term in Module call cleanup Goal Cleanup Executes the procedure call Goal When Goal succeeds deterministically is cut fails or raises an exception Cleanup is executed call residue Goal Residue Executes the procedure call Goal Any floundered goals and the variables they are blocked on occur as VarSet Goal pairs in Residue callable X X is currently instantiated to a compound term or an atom character count 4 Stream Count Count characters have been read from or written to the stream Stream clause Head Body clause Head Body Ref clause Head Body Ref There is an interpreted clause whose head is Head whose body is Body and whose unique identifier is Ref close Stream Closes stream Stream 382 SICStus Prolog compare Op Term1 Term2 Op is the result of comparing the terms Term1 and Term2 compile Files Compiles in core the cl
168. List Length If List is instantiated to a list of determinate length then Length will be unified with this length If List is of indeterminate length and Length is instantiated to an integer then List will be unified with a list of length Length The list elements are unique variables If Length is unbound then Length will be unified with all possible lengths of List numbervars Term N M Unifies each of the variables in term Term with a special term so that write Term or writeq Term see Section 7 1 3 Term I O page 80 prints those variables as A i mod 26 1 26 where i ranges from N to M 1 N must be instantiated to an integer If it is 0 you get the variable names A B Z Al B1 etc This predicate is used by listing 0 1 see Section 7 6 State Info page 104 halt ISO Causes Prolog to exit back to the shell In recursive calls to Prolog from C this predicate will return back to C instead halt Code ISO Causes the Prolog process to immediately exit back to the shell with the return code Code even if it occurs in a recursive call from C op Precedence Type Name ISO Declares the atom Name to be an operator of the stated Type and Precedence see Section 2 6 Operators page 37 Name may also be a list of atoms in which case all of them are declared to be operators If Precedence is 0 then the operator properties of Name if any are cancelled current op Precedence Type Op ISO T
169. Lists of Character Codes 369 36 I O on Lists of Character Codes This package defines I O predicates that read from or write to a list of character codes a string There are also predicates to open a stream referring to a list of character codes The stream may be used with general Stream I O predicates To load the package enter the query use_module library charsio format_to_chars Format Arguments Chars format_to_chars Format Arguments S0 S Prints Arguments into a list of character codes using format 3 see Section 7 1 3 Term I O page 80 Chars is unified with the list alternatively SO and S are unified with the head and tail of the list respectively write_to_chars Term Chars write_to_chars Term S0 S A specialized format_to_chars 3 4 Writes Term into a list of character codes using write 2 see Section 7 1 3 Term I O page 80 Chars is unified with the list alternatively SO and S are unified with the head and tail of the list respectively atom_to_chars Atom Chars atom_to_chars Atom S0 S A specialized format to chars 3 4 Converts Atom to the list of characters com prising its name Chars is unified with the list alternatively S0 and S are unified with the head and tail of the list respectively number to chars 4 Number Chars number to chars Number S0 S A specialized format to chars 3 4 Converts Number to the list of characters comprising it
170. Mode is one of read Open the file for input write Open the file for output The file is created if it does not already exist the file will otherwise be truncated append Open the file for output The file is created if it does not already exist the file will otherwise be appended to If FileName is an integer it is assumed to be a file descriptor passed to Prolog from C The file descriptor is connected to a Prolog stream invoking the POSIX function fdopen which is unified with Stream Options is a list of zero or more of type T Specifies whether the stream is a text or binary stream Default is text close X ISO If X is a stream the stream is closed If X is the name of a file opened by see 1 or tell 1 the corresponding stream is closed absolute_file_name RelativeName AbsoluteName True if RelativeName can be expanded to an absolute file name an atom Absolute Name according to the filename syntax rules see Section 7 1 Input Output page 71 This predicate will first search for a file with the suffix p1 added to the name given as an argument If this fails it will look for a file with no extra suffix added If a file is found AbsoluteName is its absolute file name is returned Otherwise AbsoluteName is a valid expansion of RelativeName absolute_file_name 2 does not produce alternative expansions via backtracking If RelativeName is user then AbsoluteName is also unified with user this filename sta
171. P gt Q If P then Q else false using first solution of P only File Files Updates the program with interpreted clauses from File and Files Command Not a built in predicate reserved syntax for commands and declarations Query Not a built in predicate reserved syntax for queries Head Body Not a built in predicate reserved syntax for clauses P Q PorQ X 2 Y The terms X and Y are unified Term List Term List The functor and arguments of the term Term comprise the list List X Y X is numerically equal to Y Terml Term2 The terms Term1 and Term are strictly identical X Y X is not numerically equal to Y X lt Y X is less than or equal to Y X gt Y X is greater than Y X gt Y X is greater than or equal to Y X P Executes the procedure call P A P Goal P is not provable Terml1 Term2 The terms Term and Term are not strictly identical 380 SICStus Prolog iX lt Y X is less than Y Term1 lt Term2 The term Term1 precedes or is identical to the term Term2 in the standard order Term1 gt Term2 The term Term1 follows the term Term2 in the standard order Term1 gt Term2 The term Term1 follows or is identical to the term Term2 in the standard order Term lt Term2 The term Term1 precedes the term Term2 in the standard order 2 X Y X and Y are either syntactically identical or syntactically non u
172. PSIZE environment 10 PROLOGMAXSIZE environment sess 10 prompt 2 e a EE ere REG eee yak Ea eta 125 public 1 declaration sess 56 p t lolsschengha rene MNEOUUIT DU CURA EDD IE Dd 88 put 2 boe ers bra d erra eed 88 put assoc Zeiccilniseidci tique ve ug repe nvid 192 P tz att S D ENKE rE O Va pUpEE CU eR AR a cata 193 put label Miri cr peti gra CREE dpt bd eed 219 put Labei b ci besoin bs deberia M 219 Q quasi skip debugger command 66 QU 2 yeo svensk aise macer Rev PIS 211 queue head 8 coils a peed ee ean FCR 211 queue head list 3 isse 211 queue la st 3 cot A pg E QU QUUD 211 queue last list 3 ond eri era 211 queue length 2 4 bg PRU ELDER PER 212 R raise exception debugger command 68 raise exception 1 isses 101 random i loved eae ees eee ak eas E qu Siw dees 213 Td BE 213 random ugraph 3 sse 223 random wgraph 4 AAA Rete VP EPI 227 Pandseq Brita epe CE RE EE da UR 213 Lands iii Pieces em arp Ue ea 213 range to tds Daria rera Ra 287 POP Woe Rete Lp SED Lb LIMU e D beo bL 233 CAL ii it uper RERO te Rp das A iR fedis 234 rd noblock 1 v sei We de pee e eke eels 233 416 r achable 3 i hup mr ep ERES 223 227 Tead l ees ile cR EU RRCURC ION SERES ERE CERT 80 read 2 iia ida dade eta 80 read from chars 2 u n nei i EECA DE E eee eee 369 read term 2 i gatene rr lado 81 read ter aria ar ibe da 81 recons l
173. Prefix followed by the elements in Suffix It can be used to form Combined or it can be used to find Prefix and or Suffix from a given Combined delete List Element Residue Residue is the result of removing all identical occurrences of Element in List is list List List is a proper list last List Last Last is the last element in List Example last x y z Z Z 2z yes max list 4 ListOfNumbers Max Max is the largest of the elements in ListOfNumbers member Element List Element is a member of List It may be used to test for membership in a list but it can also be used to enumerate all the elements in List Example member X a b c X a X b X c yes memberchk Element List Element is a member of List but memberchk 2 only succeeds once and can therefore not be used to enumerate the elements in List Example 202 SICStus Prolog memberchk X a b c X a no min_list ListOfNumbers Min Min is the smallest of the numbers in the list ListOfNumbers nextto X Y List X and Y appears side by side in List Example nextto X Y 1 2 3 mai Y 27 X 2 Y 37 no no_doubles List List contains no duplicated elements This is true when dif X Y holds for all pairs of members X and Y of the list non member Element List Element does not occur in List This is true when dif Element Y holds for all members Y of the list nth N
174. Runtime Systems version Message Adds the atom Message to the list of introductory messages not available in Runtime Systems volatile Specs Not a built in predicate volatile declaration when Condition Goal Blocks Goal until the Condition is true write Term write Stream Term Writes the term Term on the stream Stream or on the current output stream write_canonical Term write_canonical Stream Term Writes Term on the stream Stream or on the current output stream so that it may be read back Summary of Built In Predicates 393 write_term Term Options write_term Stream Term Options Writes the term Term on the stream Stream or on the current output stream with extra Options writeq Term writeq Stream Term Writes the term Term on the stream Stream or on the current output stream quoting names where necessary zip Switches on debugging in zip mode not available in Runtime Systems 394 SICStus Prolog Full Prolog Syntax 395 Full Prolog Syntax A Prolog program consists of a sequence of sentences or lists of sentences Each sentence is a Prolog term How terms are interpreted as sentences is defined below see Sentence page 396 Note that a term representing a sentence may be written in any of its equivalent syntactic forms For example the 2 ary functor could be written in standard prefix notation instead of as the usual infix operator Terms are written as seque
175. S term sei ee ua Feli de tas Voie hi 135 COTOULINING sialon se logan PR Ragan os gate 119 COUNLEE Minch eeepc Bi My Shite he S Wade 121 cross reference opea ena EE nes 377 current input stream 0 eee eee 72 current output stream 00 cee eee eee eee 72 CU tare eet Wier tee eA ended pe tei ual Se d 36 44 CUT STOOD Lese da eee kb aA mo AR Ra safe hipaa RR 37 clit redorta vk ERREUR NER we ele Rahs 37 cyclic terns A bs Cyan ue WES 36 81 83 D CACMON iinet Dm 340 databases sso e asp dr eve mST 115 235 database default 0 0 00 cece eee eee eee ee 237 dbsSDecieces per caves vi pe QU te Mee Rare eas 236 DOG txt EE qu cake kinins bE ERU da EE 76 debug Options pdari cscs vena eck deed Cea p Ee pus 65 debugging scien tees e tv de bes pt hb ian 59 debugging messages 00 2 eee e eee eee ee 63 debugging predicates 0c eee eee 61 424 declaration attribute 0 e eee eee eee 193 declaration block 000 e eee eee eee 55 declaration dynamic esses esses 54 declaration meta predicate 50 56 declaration mode iissssessseeesseesseeseeA 56 declaration module 0 cece eee eee eee 56 declaration multifile 0 0 02 52 54 declaration operator seen 53 declaration predicate 0 cece eee eee eee 53 declaration public 2 0 cee eee eee 56 decla
176. SICStus When it is started a goal passed in Hook is evaluated Hook must have the form Address Goal where Address must be unifiable with Host Port and Goal must be instantiated to a goal Example linda Host Port my_module mypred Host Port will call mypred 2 in module my_module when the server is started mypred 2 could start the client processes save the address for the clients etc Note that the module must be present in Goal Chapter 26 Linda Process Communication 233 26 2 Client The clients are one or more sicstus processes which have connection s to the server To load the package enter the query use module library linda client Some of the following predicates fail if they don t receive an answer from the Linda server in a reasonable amount of time That time is set with the predicate 1inda timeout 2 linda client Address Establishes a connection to a Linda server specified by Address The Address is of the format Host PortNumber as given by linda O and linda 1 It is not possible to be connected to two Linda servers in the same time This predicate can fail due to a timeout close client Closes the connection to the Linda server linda timeout Old Time New Time This predicate controls Linda s timeout OldTime is unified with the old timeout and then timeout is set to NewTime The value is either off or of the form Sec onds Milliseconds The former value indicates that the time
177. SICStus Prolog help spot such efficiency bugs It is printed as indicating that foo 3 could backtrack and find alternative solutions or otherwise S is a spy point indicator It is printed as indicating that there is a spy point on foo 3 or M 8 denoting no spy point The first number is the unique invocation identifier It is nondecreasing regardless of whether or not you are actually seeing the invocations provided that the debugger is switched on This number can be used to cross correlate the trace messages for the various ports since it is unique for every invocation It will also give an indication of the number of procedure calls made since the start of the execution The invocation counter starts again for every fresh execution of a command and it is also reset when retries see later are performed The number following this is the current depth i e the number of direct ancestors this goal has The next word specifies the particular port Call Exit Redo Fail or Exception T is a subterm trace This is used in conjunction with the command set subterm described below If a subterm has been selected T is printed as the sequence of commands used to select the subterm Normally however T is printed as indicating that no subterm has been selected The goal is then printed so that you can inspect its current instantiation state The final is the prompt indicating
178. SICStus Prolog User s Manual by the Intelligent Systems Laboratory Swedish Institute of Computer Science PO Box 1263 SE 164 29 Kista Sweden Release 3 7 September 1998 Swedish Institute of Computer Science sicstus request sics se http www sics se isl sicstus html Copyright 1995 SICS Swedish Institute of Computer Science PO Box 1263 SE 164 29 Kista Sweden 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 SICS Introduction 1 Introduction Prolog is a simple but powerful programming language developed at the University of Marseilles Roussel 75 as a practical tool for programming in logic Kowalski 74 From a user s point of view the major attraction of the language is ease of programming Clear readable concise programs can be written quickly with few errors For an introduction to programming in Prolog readers are recommended to consult
179. SP_fputc C function 0 008 145 SP_fputs C function 008 145 SP free C function 0 0 004 140 SP_get_address C function 138 SP get argO C function 05 138 SP get atom C function ssu 138 SP_get_float C function 138 SP get functor C function 138 SP get integer C function 138 SP get list C function sss 138 SP get list chars C function 138 SP get list n chars C function 138 SP_get number chars C function 138 SP get string C function 138 SP getc C function 0048 145 SP initialize C function 151 SP INTEGER C macro sseeeeeeee ees 139 SP is atom C function 004 139 SP is atomic C function sss 139 SP is compound C function 139 SP is float C function 4 139 SP is integer C function 139 SP islistO C function 0 04 139 SP is number C function ss 139 SP is variable C function 139 SP load C function 0 004 153 SP make stream C function 147 SP malloc C function ssssss
180. Sets the user stream post hook to hook 8 5 3 1 Writing User stream Hooks The user stream hook is if defined called during SP initialize O SP_set_user_stream_hook and SP set user stream post hook must therefore be called before SP_initialize is called It has the following prototype SP stream user stream hook int which If the hook is not defined SICStus will attempt to open the standard TTY console versions of these streams If they are unavailable such as for windowed applications under Windows the result is undefined It is called three times one for each stream The which argument indicates which stream it is called for The value of which is one of SP STREAMHOOK STDIN Create stream for standard input SP STREAMHOOK STDOUT Create stream for standard output Chapter 8 Mixing C and Prolog 149 SP_STREAMHOOK_STDERR Create stream for standard error The hook should return a standard SICStus I O stream as described in Section 8 5 2 Defining a New Stream page 146 8 5 3 2 Writing User stream Post hooks The user stream post hook is if defined called after all the streams have been defined once for each of the three standard streams It has a slightly different prototype void user_stream_post_hook int which SP_stream str where str is a pointer to the corresponding SP_stream structure There are no requirements as to what this hook must do the default behavior is to do nothing at all The p
181. Shell setenv EPROLOG usr local bin sicstus 1 11 2 Basic Configuration If the following lines are not present in emacs we suggest they are added so that the font lock mode syntax coloring support is enabled for all major modes in Emacs that support it global font lock mode t setq font lock maximum decoration t If one wants to add font locking only to the prolog mode the two lines above could be replaced by add hook prolog mode hook turn on font lock If the background color of Emacs is dark and it is difficult to read the code because of the chosen colors then it might be useful to add setq font lock background mode dark 1 11 3 Usage A prolog process can be started by choosing Run Prolog from the Prolog menu by typing C c RET or by typing M x run prolog It is however not strictly necessary to start a prolog process manually since it is automatically done when consulting or compiling if needed The process can be restarted i e the old one is killed and a new one is created by typing C u C c RET Programs are run and debugged in the normal way with terminal I O via the prolog buffer The most common debugging predicates are available from the menu or via key bindings 20 SICStus Prolog A particularly useful feature under the Emacs interface is source linked debugging This is enabled or disabled using the Prolog Source level debugging menu entry It can also be enabled by setting the Emacs v
182. The call is made after SICStus Prolog s signal handler installation but before the built in predicates version O and initialization O are called Calling Prolog from functions invoked through this hook is not supported This hook is not available in Runtime Systems Chapter 8 Mixing C and Prolog 151 typedef void SP_VoidFun void SP_VoidFun SP_set_interrupt_hook SP_VoidFun The installed function is called on occasions like expansion of stacks garbage collection and printouts in order to yield control to special consoles etc for interrupt checking Calling Prolog from functions invoked through this hook is not supported This hook is not available in Runtime Systems 8 8 Runtime Systems It is possible to mix C and Prolog code to create stand alone applications Runtime Systems In a Runtime System there are some differences in the behavior of the Prolog engine and many built in predicates are omitted or have limited functionality e No top level e No debugger e No compiler e No progress or error messages while loading files e No profiling e No OR parallelism e No redefinition warnings e No signal handling except as installed by SP_signal e Uncaught exceptions are returned to C e The predicates halt 0 abort 0 and reinitialise O will return to C e You have to supply a main program and explicitly initialize the Prolog engine with SP_ initialize 8 8 1 Initializing the Prolog Engine You must cal
183. The first set is available in an alternative version where the stream is specified explicitly The rule is that the stream is the first argument which defaults to the current input or output stream depending on context nl ISO nl Stream ISO A new line is started on Stream by printing an LFD If Stream is connected to the terminal its buffer is flushed geto N ISO geto Stream N ISO N is the character code of the next character read from Stream If all characters of Stream have been read N is 1 and further calls to get0 2 for the same stream will then raise an exception unless the stream is connected to the terminal 88 SICStus Prolog These predicates are called get_code 1 2 in the ISO Prolog standard peek_char N ISO peek_char Stream N ISO N is the character code of the next character from Stream or 1 if all characters of Stream have been read N The character is not actually read it is only looked at and is still available for subsequent input These predicates are called peek_code 1 2 in the ISO Prolog standard get 7N get Stream N Same as get0 2 except N is the character code of the next character that is not a layout char see Token String page 398 read from Stream skip N skip Stream N Skips just past the next character code N from Stream N may be an arithmetic expression skip_line skip_line Stream Skips just past the next LFD from Stream put N ISO put Stream
184. The following predicate can be used for computing the set of variables that are transitively connected via constraints to some given variables fd closure Vars Closure Given a list Vars of domain variables Closure is the set of variables including Vars that can be transitively reached via constraints posted so far Chapter 30 Constraint Logic Programming over Finite Domains 287 30 8 3 FD Set Operations The domains of variables are internally represented compactly as FD set terms The details of this representation are subject to change and should not be relied on Therefore a number of operations on FD sets are provided as such terms play an important role in the interface The following operations are the primitive ones is_fdset Set Set is a valid FD set empty_fdset Set Set is the empty FD set fdset parts Set Min Max Rest Set is an FD set which is a union of the non empty interval Min Max and the FD set Rest and all elements of Rest are greater than Max 1 Min and Max are both integers or the atoms inf and sup denoting minus and plus infinity respectively Either Set or all the other arguments must be ground The following operations can all be defined in terms of the primitive ones but in most cases a more efficient implementation is used empty interval 4 Min Max Min Max is an empty interval fdset interval Set Min Max Set is an fdset which is the non empty interval Min Max fds
185. The list List1 must consist of items of the form Key Value These items are sorted into order according to the value of Key yielding the list List2 No merging takes place This predicate is stable i e if K A occurs before K B in the input then K A will occur before K B in the output The time and space complexity of this operation is at worst O N lg N where N is the length of List1 Chapter 7 Built In Predicates 99 7 4 Control P Q ISO P and Q P Q ISO P or Q ISO See Section 2 5 Cut page 36 P ISO Fails if the goal P has a solution and succeeds otherwise This is not real negation P is false but a kind of pseudo negation meaning P is not provable It is defined as if by P P fail NEC No cuts are allowed in P Remember that with prefix operators such as this one it is necessary to be careful about spaces if the argument starts with a For example T5 P Q is this operator applied to the conjunction of P and Q but P Q would require a predicate 2 for its solution The prefix operator can however be written as a functor of one argument thus P Q is also correct P gt Q R ISO Analogous to if P then Q else R and defined as if by P gt Q R P Q P gt Q R R except the scope of any cut in Q or R extends beyond the if then else construct No cuts are allowed in P Note that this form of if then else only e
186. The notation name arity is therefore used when it is necessary to refer to a predicate unambiguously e g concatenate 3 specifies the predicate which is named concatenate and which takes 3 arguments In general a predicate spec takes the form name arity With the introduction of the module system this spec is only defined relative to the current module An absolute predicate spec must include a module prefix module name arity 6 SICStus Prolog Development and Runtime Systems The full Prolog system with top level compiler debugger etc is known as the Development System On some platforms both a sequential and an OR parallel Development System can be built The OR parallel Development System is also known as Muse OR parallelism executes clauses and disjunctions of a predicate in parallel and is useful for search and all solutions style programming No change or annotations of the programs are necessary but sometimes more parallelism may be utilized if the program is modified The main issue is to avoid side effects that might serialize the search Except for some few exceptions Muse preserves the full functionality of SICStus Prolog Muse is still an experimental system and is not formally supported It is possible to link user written C code with a subset of SICStus Prolog to create stand alone applications called Runtime Systems Only sequential Runtime Systems are available When introducing a built in predicate any limitat
187. Tips Some general tips and tricks for using the SICStus mode and Emacs in general are given here 1 11 6 1 Font locking When editing large files it might happen that font locking is not done because the file is too large Typing M x lazy lock mode results in only the visible parts of the buffer being highlighted which is much faster If the font locking seems to be incorrect then choose Fontify Buffer from the Prolog menu 1 11 6 2 Auto fill mode Auto fill mode is enabled by typing M x auto fill mode This enables automatic line breaking with some features For example the following multiline comment was created by typing M followed by the text The second line was indented and a was added automatically dynamics A list of pit furnace dynamic instances 1 11 6 3 Speed There are several things to do if the speed of the Emacs environment is a problem e First of all make sure that prolog el and pltrace el are compiled i e that there is a prolog elc and a pltrace elc file at the same location as the original files To do the compilation start Emacs and type M x byte compile file RET Path RET where Path is the path to the e1 file Do not be alarmed if there are a few warning messages as this is normal If all went well there should now be a compiled file which is used the next time Emacs is started Chapter 1 How to Run Prolog 25 e The next thing to try is changing the setting of pro
188. X amp lives X gt exists Y woman Y amp loves X Y where amp and gt are infix operators defined by op 900 xfx gt op 800 xfy amp op 300 xfx The grammar follows 184 SICStus Prolog sentence P gt noun_phrase X P1 P verb phrase X P1 noun phrase X P1 P gt determiner X P2 P1 P noun X P3 rel clause X P3 P2 noun phrase X P P gt name X verb phrase X P trans verb X Y P1 noun phrase Y P1 P verb phrase X P gt intrans verb X P rel clause X P1 P1 amp P2 gt that verb phrase X P2 rel_clause _ P P gt determiner X P1 P2 al1 X P1 gt P2 gt every determiner X P1 P2 exists X P1 P2 gt a noun X man X gt man noun X woman X gt woman name john gt john trans_verb X Y loves X Y gt loves intrans_verb X lives X gt lives 10 5 9 Muse FLI Example This example illustrates the techniques used in foreign language interface programming in Muse Let us assume we want to count the number of solutions of some problem as well as the number of solutions produced by each worker The following C file count c defines some procedures that can be used for this purpose include lt sicstus sicstus h gt static int overall_counter_lock static int worker_counters overall_counter void allocate counters 1 overall counter lock int
189. X m N 1 2 X i I gt exactly I X 1 X i 1 X i 1 X m N 3 N 0 gt X i I X m I 4 N m gt X 1 1 X m I use_module library clpfd the entrypoint exactly I Xs N dom_suspensions Xs Susp fd_global exactly I Xs N state Xs N Susp dom_suspensions dom suspensions X Xs dom X Susp dom suspensions Xs Susp the solver method multifile clpfd dispatch global 4 clpfd dispatch_global exactly I _ _ state Xs0 NO state Xs N Actions exactly solver I XsO Xs NO N Actions exactly solver I XsO Xs NO N Actions ex filter XsO Xs NO N I length Xs M N 0 Actions exit Ps ex neq Xs I Ps N M gt Actions exit Ps ex_eq Xs I Ps N50 N M gt Actions J Actions fail rules 1 2 filter the X s decrementing N ex filter N N _ ex filter X Xs Ys L N I X I M is L 1 ex filter Xs Ys M N I ex filter X Xs YsO L N I fd set X Set fdset member I Set YsO X Ys ex filter Xs Ys L N I ex filter Xs Ys L N I ex filter Xs Ys L N I 290 SICStus Prolog rule 3 all must be neq I ex_neq Xs I Ps fdset singleton SetO I fdset complement SetO Set eq all Xs Set Ps rule 4 all must be eq I ex eq Xs I Ps fdset singleton Set I eq all Xs Set Ps eq all _ eq_all X
190. a query portray message Severity Message user portray message Severity Message A hook predicate Called by print message 2 before printing the message If this succeeds the default message for printing Message is overridden and nothing more is printed Chapter 7 Built In Predicates 103 The built in predicates may raise exceptions as follows on errors Usually the goal and the argument number causing the error are contained in the exception instantiation_error Goal ArgNo Goal was called with insufficiently instantiated variables type_error Goal ArgNo TypeName Culprit Goal was called with the wrong type of argument s TypeName is the expected type and Culprit what was actually found domain_error Goal ArgNo Domain Culprit Goal was called with argument s of the right type but with illegal value s Domain is the expected domain and Culprit what was actually found existence error Goal ArgNo Object Type Culprit Reserved Something does not exist as indicated by the arguments If the unknown flag see prolog_flag 3 is set to error this error is raised with ArgNo set to 0 when an undefined predicate is called permission error Goal Operation Object Type Culprit Reserved The Operation is not permitted on Culprit of the ObjectType context _error Goal Context Type Command Type The CommandType is not permitted in Context Type syntax_error Goal Position Message Tokens AfterError
191. ader 229 Socket select b iiie vied FECE 230 socket sele ct 6 i soie itr Rp vex Helens 230 SOEU 2s E E WRAP NU He UP DETUR Puls 98 SOURCE til Dira dede yr ER PR te 75 source file 2 0 c yn e HP VEPEDIPPEQ EER 75 source_info prolog flag ooooooooomoooo 108 SP ATOM Csmacro Aaa ae bes 139 SP atom from string C function 136 SP atom length C function 136 SP close query C function 142 SP compare C function sss 140 SP COMPOUND C macro sees 139 SP cons functor C function 137 SP cons list C function sss 137 SP continue C function sss 143 SP_CTYPE environment s sess esss se 10 SP cut query C function sss 142 SP err o Caqacro cele er v D eens 128 SP ERROR C macro resti bresain er RE RE 128 SP error message C function 128 SP event C function 0 0 005 142 SP exception term C function 144 Predicate Index SP_FAILURE C macro ee cece eee eee 128 SP fclose C function 0 00 145 SP_fflush C function 0 055 145 SP_fgetc C function 008 145 SPZFLOAT C Macro epeei ere eer Ep CURAS ERE 139 SP force interactive C function 151 SP fprintf C function s sss 145
192. age collector is called explicitly The atom garbage collector will find all references to atoms from the Prolog specific memory areas including SP_term_refs and arguments passed from Prolog to foreign language functions However atoms created by SP_atom_from_string and merely stored in a local variable are endangered by garbage collection The following functions make it possible to protect an atom while it is in use The operations are implemented using reference counters to cater for multiple independent use of the same atom in different foreign resources int SP_register_atom unsigned long a Registers the atom a with the Prolog memory manager by incrementing its reference counter Returns a nonzero value if the operation succeeds int SP_unregister_atom unsigned long a Unregisters the atom a with the Prolog memory manager by decrementing its reference counter Returns a nonzero value if the operation succeeds 8 3 2 Creating Prolog Terms These functions create a term and store it as the value of an SP_term_ref which must exist prior to the call They return zero if the conversion fails as far as failure can be detected and a nonzero value otherwise assigning to t the converted value int SP_put_variable SP_term_ref t Assigns to t a new Prolog variable int SP put integer SP term ref t long 1 Assigns to t a Prolog integer from a C long integer int SP put float SP term ref t double d Assigns to t a Prolog float fr
193. ain 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 domain X 5 6 7 1 domain Y 3 4 5 6 domain Z 1 6 7 8 yes 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 must be attributed then get_atts Other frozen Fb has a pending goal gt put atts ther frozen Fa Fb rescue conjunction put atts O0ther frozen Fa rescue the pending goal var Other gt J5 Goals Goals Fa verify_attributes _ _ 0O attribute_goal Var Goal get_atts Var frozen Goal myfreeze X Goal put_atts Fresh frozen Goal interpretation as goal 198 SICStus Prolog Fresh X Assuming that this code lives in file myfreeze pl we would use it via use module myfreeze myfreeze X print bound x X X 2 bound x 2 side effect X 2 bindings The two solvers even work together myfreeze X print bound x X domain X 1 2 3 domain Y 2 10 X Y bound x 2 side effect X 2 bindings Y 2
194. aking a directed graph undirected top_sort Graph Sorted Finds a topological ordering of a Graph and returns the ordering as a list of Sorted vertices Fails iff no ordering exists i e iff the graph contains cycles Takes O N 2 time max_path V1 V2 Graph Path Cost Path is a longest path of cost Cost from V1 to V2 in Graph there being no cyclic paths from V1 to V2 Takes O N 2 time min path V1 V2 Graph Path Cost Path is a shortest path of cost Cost from V1 to V2 in Graph Takes O N 2 time min paths Vertex Graph Tree Tree is a tree of all the shortest paths from Vertex to every other vertex in Graph This is the single source shortest paths problem path Vertex Graph Path Given a Graph and a Vertex of Graph returns a maximal Path rooted at Vertex enumerating more paths on backtracking Chapter 23 Unweighted Graph Operations 223 reduce Graph Reduced Reduced is the reduced graph for Graph The vertices of the reduced graph are the strongly connected components of Graph There is an edge in Reduced from u to v iff there is an edge in Graph from one of the vertices in u to one of the vertices in v reachable Vertex Graph Reachable Given a Graph and a Vertex of Graph returns the set of vertices that are reachable from that Vertex including Vertex itself Takes O N 2 time random_ugraph P N Graph Where P is a probability unifies Graph with a random graph of vertices
195. al blocked goals in G1 Gj 1 to become unblocked then these goals may become reordered The internal order of any two goals that were blocked on the same variable is retained however Another consequence is that a query may be derived consisting entirely of blocked goals Such a query is said to have floundered The top level checks for this condition If detected the outstanding blocked subgoals are printed on the standard error stream along with the answer substitution to notify the user that the answer s he has got is really a speculative one since it is only valid if the blocked goals can be satisfied A goal is blocked if certain arguments are uninstantiated and its predicate definition is annotated with a matching block declaration see Section 5 2 4 Block Declarations page 55 Goals of certain built in may also be blocked if their arguments are not sufficiently instantiated When this mechanism is used the control structure resembles that of coroutines suspending and resuming different threads of control When a computation has left blocked goals behind the situ ation is analogous to spawning a new suspended thread When a blocked goal becomes unblocked the situation is analogous to temporarily suspending the current thread and resuming the thread to which the blocked goal belongs 36 SICStus Prolog 2 4 Occurs Check It is possible and sometimes useful to write programs which unify a variable to a term in which that v
196. allocate counters c allocate counters foreign init counters c init counters foreign incr counter c incr counter integer l foreign get counter c get counter integer integer 186 load foreign resource count allocate counters count Goal statistics walltime Start count solutions Goal statistics walltime End display counts N Time is End Start format Total d solutions in 3d seconds count solutions Goal init counters Goal incr counter fail count solutions display counts N get counter 1 N muse num workers M display worker counts 0 M display worker counts M M display worker counts W M get counter W C C 0 gt true format Solutions by worker d d n W C s Wi is W 1 display worker counts Wi M SICStus Prolog n N Time This example is compiled and executed as follows to count the number of solutions to the 8 queens problem see Section 3 2 Run Example page 41 gcc c count c sicstus P compile count queens muse flag num workers 3 count queens 8 _ Solutions by worker 0 39 Solutions by worker 1 31 Solutions by worker 2 22 Total 92 solutions in 0 070 seconds NS yes Chapter 11 The Prolog Library 187 11 The Prolog Library The Prolog library comprises a number of packages which are thought to be useful in a nu
197. ample illustrates the use of the meta logical predicates var 1 arg 3 and functor 3 see Section 7 7 Meta Logic page 110 The procedure call variables Term L instantiates variable L to a list of all the variable occurrences in the term Term e g variables d U V X DU V U DV L L U V X DU V U DV 182 SICStus Prolog variables X X LO L var X L LO variables T LO L nonvar T functor T _ A variables 0 A T LO L variables A A _ LO L L LO variables A0 A T LO L Y AO lt A Al is AO41 arg A1 T X variables X LO L1 variables A1 A T Li L 10 5 6 Use of Term Expansion This example illustrates the use of user term_expansion 2 4 to augment the built in predicate expand term 2 which works as a filter on the input to compile and consult The code below will allow the declaration wait 3 as an alias for block Wait declarations were used in previous versions of SICStus Prolog Note the multifile declaration which prevents this user term expansion 2 4 clause from erasing any other clauses for the same predicate that might have been loaded op 1150 fx wait multifile user term expansion 2 user term expansion wait F N block Head functor Head F N wb args N Head wb args 1 Head arg 1 Head wb args N Head Y N gt 1 arg N Head 7 Ni is N 1 wb_args N1
198. ample of a constraint with all methods defined consider the following library constraint defining a disequation between two domain variables x y X Y X in MY Y in MX gt x y X Y X in dom Y Y in dom X x y X Y X in dom Y x Sy X Y X in Y The following sections provide more precise coding rules and operational details for indexicals X in R denotes an indexical corresponding to a constraint C S denotes the current store 296 SICStus Prolog 30 9 6 Execution of Propagating Indexicals Consider the definition of a constraint C containing a propagating indexical X in R Let TV X C S denote the set of values for X that can make C true in some ground extension of the store S Then the indexical should obey the following coding rules e all arguments of C except X should occur in R e if R is ground in S S R TV X C S If the coding rules are observed S R can be proven to contain TV X C S for all stores in which R is monotone Hence it is natural for the implementation to wait until R becomes monotone before admitting the propagating indexical for execution The execution of X in R thus involves the following e If D X S is disjoint from S R a contradiction is detected e If D X S is contained in S R D X S does not contain any values known to be incompatible with C and the indexical suspends unless R is ground in S in which case C is detected as entailed e Otherwi
199. and 2147483647 time_out 3 is implemented by raising and handling time_out exceptions so any exception handler in the scope of Goal must be prepared to pass on time_out exceptions The following incorrect example shows what can happen otherwise time_out on_exception Q repeat false true 1000 Res Q time_out Res success 376 SICStus Prolog Chapter 40 Cross Reference Producer 377 40 Cross Reference Producer This package provides a cross reference producer is a useful tool for debugging and program analysis It can be used to produce the call graph of a program and to produce a list of predicates that are used but not defined or vice versa The graph processing utilities described in previous chapters may be used to analyze the call graphs To load the package enter the query use_module library xref call_graph Files Graph Graph is the call graph see Chapter 23 UGraphs page 221 of the predicates in Files The vertices of Graph are terms of the following types def There is an edge from def to every predicate that is explicitly defined declared imported or implicitly defined in a foreign 2 3 fact use There is an edge from use to every predicate that is used in a direc tive exported or declared as public If a hook predicate such as user portray 1 is defined there is an edge from use to it too Module Name Arity Denotes a predicate occurring in one of the Files There is an edg
200. and provide automatic conversion of arguments Jasper can be operated in two different ways depending on which emulator is used as top level application the Java Runtime System or the SICStus Development System When the Java Run time System is used as a top level application the SICStus runtime kernel is loaded into the Java Runtime System When the Java Runtime System is loaded into the SICStus Development System it is loaded as any other foreign resource i e by using load_foreign_resource 1 This distinction is not visible to the programmer but it is useful to have a picture of how the interface works Note Some of the information in this chapter is a recapitulation of the information in the chapter Chapter 8 Mixing C and Prolog page 127 The intention is that this chapter should be possible to read fairly independently 9 1 Prerequisites The low level interface uses the JNI Java Native Interface to call C functions from Java The JNI is a native interface standard developed by Sun Microsystems See Section 9 7 Java Resources Online page 176 Since the interface uses the JNI it is necessary that the Java VM which is to be used has support for JNI Even though the JNI is intended as a standard not all vendors support it If your Java installation does not support the JNI Sun s Java Runtime Environment provides a minimal execution enviroment for running Java code It can be downloaded from http java sun com products jdk 1 1
201. are defined in the specific objects e g the object distributor This program heavily uses the sub 1 method We have tried to be as close as possible to the original formulation faults 1 super utility amp dynamic told 2 amp no fault is the default fault _ fail amp findall lt restart sub Sub Sub find Where Fault lt print Where Fault fail amp Chapter 32 Prolog Objects 355 findall amp print Where Fault writeseqnl Location 2 Where writeseqnl Possible Fault Fault nl amp find Where Fault self Where fault FaultNum Fault effect FaultNum S contrary S 1 exhibited S1 effect FaultNum SymptomNum exhibited SymptomNum amp find Where Fault sub Sub Sub find Where Fault amp exhibited S told S R R yes amp exhibited S symptom S Text yesno Text gt R yes R no Ja asserta told S R R yes amp restart retractall told _ _ electrical super faults Ts fuel system 1 super faults mechanical 4 super faults ys 306 lights super electrical sparking super electrical starting super electrical Ju starter motor super electrical plugs 1 super sparking Ts engine 1 super mechanical cylinders super engine distributor
202. are distinct uninstantiated variables However the query X Y X Y succeeds because the first goal unifies the two variables see Section 7 17 Misc Pred page 124 Term1 Term2 ISO The terms currently instantiating Term1 and Term2 are not literally identical 98 SICStus Prolog Term1 lt Term2 ISO The term Term1 is before the term Term2 in the standard order Term1 0 Term2 ISO The term Term1 is after the term Term2 in the standard order Term1 lt Term2 ISO The term Term1 is not after the term Term2 in the standard order Term1 0 gt Term2 ISO The term Term1 is not before the term Term2 in the standard order Some further predicates involving comparison of terms are 2 X Y X and Y are either syntactically identical or syntactically non unifiable compare 0p Term1 Term2 The result of comparing terms Term1 and Term2 is Op where the possible values for Op are if Term is identical to Term2 lt if Term is before Term2 in the standard order gt if Term1 is after Term2 in the standard order Thus compare Term1 Term2 is equivalent to Termi Term2 sort List1 List2 The elements of the list List1 are sorted into the standard order see Section 7 3 Term Compare page 97 and any identical elements are merged yielding the list List2 The time and space complexity of this operation is at worst O N lg N where N is the length of List 1 keysort List1 List2
203. are not imported but copied Even dynamic declarations methods without clauses are inherited Inheritance from dynamic objects differs in one aspect Static predicates visible in a dynamic object are not imported directly from the dynamic object but from the static object from where it was imported to the dynamic object This makes an inheriting object independent of any dynamic ancestor object after its creation 32 9 2 Object Attributes Attributes are based on an efficient term storage associated to modules The attributes for an object is collected from its ancestors and itself at compile time and used for initialization at load time The methods for accessing attributes get 1 and set 1 are inlined to primitive calls whenever possible They should hence not be redefined 346 SICStus Prolog 32 9 3 Object Instances Instances are different from other objects in that they do not inherit Instead they share the predicate name space with its class object They do however have their own attributes At creation an instance gets a copy of its class objects attributes The reserved attribute class 1 which is present in any object is used for an instance to hold its class object identifier The purpose of this is mainly to store the parameters of the class object when the instance is created 32 9 4 The Object Declaration The object declaration is only used by certain meta programming operations It consists of a fact so_type Obje
204. are reachable from that Vertex Takes O N 2 time random_wgraph P N W WeightedGraph Where P is a probability unifies WeightedGraph with a random graph of vertices 1 N where each possible edge is included with probability P and random weight in 1 W The following predicate is defined for undirected graphs only min tree WeightedGraph Tree Cost Tree is a minimum cost spanning tree of WeightedGraph with cost Cost if it exists 228 SICStus Prolog Chapter 25 Socket I O 229 25 Socket I O This library package defines a number of predicates manipulating sockets They are all rather straight forward interfaces to the corresponding BSD type socket functions with the same name except current_host 1 The reader should therefore study the appropriate documents for a deeper description The Domain is either the atom AF INET or AF_UNIX They correspond directly to the same domains in BSD type sockets AF UNIX may not be available on non UNIX platforms An Address is either AF INET Host Port or AF UNIX SocketName Host is an atomic host name Port is a portnumber and SocketName is an atom denoting a socket A reader familiar with BSD sockets will understand this immediately All streams below can be both read from and written on All I O predicates operating on streams can be used for example read 2 write 2 format 3 current stream 3 etc Socket streams are unbuffered on reads and block buffered on
205. ariable occurs thus creating a cyclic term The usual mathematical theory behind Logic Programming forbids the creation of cyclic terms dictating that an occurs check should be done each time a variable is unified with a term Unfortunately an occurs check would be so expensive as to render Prolog impractical as a programming language Thus cyclic terms may be created and may cause loops trying to print them SICStus Prolog mitigates the problem by its ability to unify compare see Section 7 3 Term Compare page 97 assert and copy cyclic terms without looping The write_term 2 built in predicate can optionally handle cyclic terms see Section 7 1 3 Term I O page 80 Unification with occurs check and predicates testing a cyclicity are available in a library package see Chapter 17 Term Utilities page 205 Other predicates usually do not handle cyclic terms well 2 5 The Cut Symbol Besides the sequencing of goals and clauses Prolog provides one other very important facility for specifying control information This is the cut symbol written It is inserted in the program just like a goal but is not to be regarded as part of the logic of the program and should be ignored as far as the declarative semantics is concerned The effect of the cut symbol is as follows When first encountered as a goal cut succeeds immedi ately If backtracking should later return to the cut the effect is to fail the parent goal i e that goal which matc
206. ariable prolog use sicstus sd to t in emacs Both these methods set the Prolog flag source_info to on The flag should be on while loading the code to be debugged and while debugging If so the debugger will display the source code location of the current goal when it prompts for a debugger command by overlaying the beginning of the current line of code with an arrow If source_info was off when the code was loaded or if it was asserted or loaded from user the current goal will still be shown but out of context Note that if the code has been modified since it was last loaded Prolog s line number information may be invalid If this happens just reload the relevant buffer Consultation and compilation is either done via the menu or with the following key bindings C c C f Consult file C c C b Consult buffer C c C r Consult region C c C p Consult predicate C c C c f Compile file C c C c b Compile buffer C c C c r Compile region C c C c p Compile predicate The boundaries used when consulting and compiling predicates are the first and last clauses of the predicate the cursor is currently in Other useful key bindings are M n Go to the next clause M p Go to the previous clause M a Go to beginning of clause M e Go to end of clause M C c Mark clause M C a Go to beginning of predicate M C e Go to end of predicate M C h Mark predicate M Go to the previous paragraph i e empty line M Go to the n
207. asks can be seen as competing for some exclusive resource serialized Starts Durations where Starts S1 Sn and Durations D1 Dn are lists of domain variables with finite bounds or integers True if Si Di lt Sj OR Sj Dj lt Si for all 1 lt i lt j lt n The serialized 2 constraint is merely a special case of cumulative 4 see below Chapter 30 Constraint Logic Programming over Finite Domains 279 serialized resource Starts Durations Resource expresses the same constraint returning in Resource a term which can be passed to order resource 2 see Section 30 4 Enumeration Predicates page 280 in order to find a consistent ordering of the tasks serialized precedence Starts Durations Precedences serialized precedence resource S arts Durations Precedences Resource express the same constraint combined with some extra precedence constraint as en coded in Precedences which should be a list of terms of the form d 1 j d Here i and j should be task numbers and d should be a positive integer or sup Each term adds the constraint Sitd lt Sj OR Sj lt Si if d is an integer Sj lt Si if dis sup serialized_precedence 3 can model a set of tasks to be serialized with sequence dependent setup times For example the following constraint models three tasks all with duration 5 where task 1 must precede task 2 and task 3 must either complete before task 2 or start at least 10 time units a
208. assive 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 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 removing the older constraint and redoing all the prop agation with the currently 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 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 I
209. ate must be added Its body defines a constraint solving method and should always succeed deterministically When a global constraint is called or resumed the solver will call this predicate to deal with the constraint StateO and State are the old and new state respectively The constraint solving method must not invoke the constraint solver recursively e g by binding variables or posting new constraints instead Actions should be unified with a list of requests to the solver Each request should be of the following form exit The constraint has become entailed and ceases to exist fail The constraint has become disentailed causing the solver to backtrack X V The solver binds X to V X ink The solver constrains X to be a member of the ConstantRange R see Syntax of Indexicals page 301 X in set S The solver constrains X to be a member of the FD set S see Section 30 8 3 FD Set Operations page 287 call Goal The solver calls the goal or constraint Goal which should be module pre fixed unless it is a built in predicate or an exported predicate of the clpfd module 286 SICStus Prolog fd global Constraint State Susp where Constraint is a constraint goal State is its initial state and Susp is a term encoding how the constraint should wake up in response to domain changes This posts the constraint Susp is a list of F Var terms where Var is a variable to suspend on and F is a functor encoding when to wake up
210. ated value get assoc Key t K V L R Val compare Rel Key K get assoc Rel Key V L R Val get_assoc _ Val _ _ Val get_assoc lt Key _ Tree _ Val get_assoc Key Tree Val get_assoc gt Key _ _ Tree Val get_assoc Key Tree Val The goal put_assoc Key OldAssoc Val NewAssoc is true when OldAssoc and NewAssoc de fine the same mapping for all keys other than Key and get_assoc Key NewAssoc Val is true Chapter 10 Programming Tips and Examples 181 put_assoc Key t Val Tree Tree t Key Val t t put_assoc Key t K V L R Val New compare Rel Key K put_assoc Rel Key K V L R Val New put_assoc Key _ _ L R Val t Key Val L R put_assoc lt Key K V L R Val t K V Tree R put_assoc Key L Val Tree put_assoc gt Key K V L R Val t K V L Tree put_assoc Key R Val Tree 10 5 4 Differentiation The goal d E1 X E2 is true if expression E2 is a possible form for the derivative of expression El with respect to X op 300 xfy binds tighter than d X X D atomic X D 1 d C X D atomic C D O d U V X DU4DV d U X DU d V X DV d U V X DU DV d U X DU d V X DV d U V X DU V U DV d U X DU d V X DV d U 4N X N Ux N1 DU integer N Ni is N 1 d U X DU d U X DU d U X DU 10 5 5 Use of Meta Logical Predicates This ex
211. ates erase 1 and instance 2 retract Fact Retracts a Fact from Self If Self is static the name and arity of Fact must be declared as a dynamic method update Fact Replaces the first fact with the same name and arity as Fact in Self by Fact If Self is static the name and arity of Fact must be declared as a dynamic method retractall Head Removes facts from Self that unify with Head If Self is static the name and arity of Fact must be declared as a dynamic method abolish Abolishes Self if dynamic augment ObjectBody augmenta ObjectBody augmentz ObjectBody ObjectBody having the form sentence 1 amp amp sentence n y is added to Self augmenta places the new clauses before any old clauses The other forms place it after any old clauses 32 8 4 The built in object utility The base object utility provides methods that could be used in user programs utility has object as its super object subs Objects Gives a list of all the children of Self supers Objects Gives a list of all parents of Self objects Objects Gives a list of all objects 344 SICStus Prolog dynamic_objects Objects Gives a list of all dynamic objects static_objects Objects Gives a list of all static objects methods Methods Gives a list of all the methods of Self dynamic methods Methods Gives a list of all dynamic methods of Self static methods Methods Gives a list of all static methods
212. ates to become defined by means of the user goal_expansion 3 mechanism They take a variable and an AccessSpec as arguments where an AccessSpec is either Attribute Attribute or a list of such The prefix may be dropped for convenience The meaning of the prefix is documented below Module get_atts Var AccessSpec Gets the attributes of Var according to AccessSpec If AccessSpec is unbound it will be bound to a list of all set attributes of Var Non variable terms cause a type error to be raised The prefixes in the AccessSpec have the following meaning Attribute The corresponding actual attribute must be present and is unified with Attribute Attribute The corresponding actual attribute must be absent The arguments of Attribute are ignored only the name and arity are relevant Module put_atts Var AccessSpec Sets the attributes of Var according to AccessSpec Non variable terms cause a type error to be raised The effects of put_atts 2 are undone on backtracking 194 SICStus Prolog Attribute The corresponding actual attribute is set to Attribute If the actual at tribute was already present it is simply replaced Attribute The corresponding actual attribute is removed If the actual attribute was already absent nothing happens A module that contains an attribute declaration has an opportunity to extend the default unification algorithm by defining the following predicate Module veri
213. atistics 2 option 109 attribute 1 declaration 193 attribute goal Zi ari siue Dev Dr Cemesu ius 194 B backtrace debugger command 67 backtracks profile_data 4 option 122 A pa BA aia dd qelbta qe abem 119 bagof rd noblock 3 sisse 234 bb delete 24 i vu Eebeggeribre ie b e 117 bb get 2 roni eds es ELO Re 116 A a Ree REA 250 Db unf bisosLW SRM Wwe 251 bb p t 2 ioc ia a A a 116 bbhiupdate 3 securities eyes EE ap date mate 117 block 1 declaration cee eee eee eee 55 blocked goals debugger command 67 break debugger command esses 68 break O Jue pP bi dre dd 16 125 Predicate Index C Biscuits E O ae p d 80 Cai tort e didn rA HR 100 call cleanup 2 ua etu kv brum 101 call graph 2 un here dete ee raten eee E eer eua 377 call residue 2 i esie rebns 120 261 callable 1i 5 ka au karte EET UPPER 110 calls profile data 4 option 122 card 2 boolean cardinality 241 ceiling 1 function csse 95 character count 2 lesen 91 character escapes prolog flag 106 choice statistics 2 option 109 choice points profile data 4 option 122 CHOICESTKSIZE environment sss 10 chr der Oir 317 chr debugging O esses 317 chr DE aS HS d uu ce ek ene ipee cm aede eek ea bls 318 chro nodeb g O c
214. atom sup plus infinity True if the variables all are elements of the range Min Max Cannot be reified X in Range defines a membership constraint X is an integer or a domain variable and Range is a ConstantRange see Syntax of Indexicals page 301 True if X is an element of the range X in set FDSet defines a membership constraint X is an integer or a domain variable and FDSet is an FD set term see Section 30 8 3 FD Set Operations page 287 True if X is an element of the FD set in 2 and in set 2 constraints can be reified They maintain domain consistency and their reified versions detect domain entailment and disentailment see Section 30 7 The Constraint System page 283 30 3 3 Propositional Constraints Propositional combinators can be used to combine reifiable constraints into propositional formulae over such constraints Such formulae are goal expanded by the system into sequences of reified constraints and arithmetic constraints For example X 4 Y 6 expresses the disjunction of two equality constraints The leaves of propositional formulae can be reifiable constraints the constants 0 and 1 or 0 1 variables New primitive reifiable constraints can be defined with indexicals as described in Sec tion 30 9 Defining Primitive Constraints page 290 The following propositional combinators are available HN Q True if the constraint Q is false Chapter 30 Constraint Logic Programming over Fi
215. ault the answer constraint only shows the projection of the store onto the variables that occur in the query but not any constraints that may be attached to these variables nor any domains or constraints attached to other variables This is a conscious decision as no efficient algorithm for projecting answer constraints onto the query variables is known for this constraint system It is possible however to get a complete answer constraint including all variables that took part in the computation and their domains and attached constraints This is done by asserting a clause for the following predicate clpfd full_answer A dynamic hook predicate If false the default the answer constraint only contains the domains of the query variables If true the answer constraints contains the domains and any attached constraints of all variables 30 7 The Constraint System 30 7 1 Definitions The constraint system is based on domain constraints and indexicals A domain constraint is an expression X I where X is a domain variable and I is a nonempty set of integers A set S of domain constraints is called a store D X S the domain of X in S is defined as the intersection of all I such that X I belongs to S The store is contradictory if the domain of some variable is empty otherwise it is consistent A consistent store S is an extension of a store S iff for all variables X D X S is contained in D X S The following definitions ada
216. auses in text file s Files compound X X is currently instantiated to a term of arity gt 0 consult Files Updates the program with interpreted clauses from file s Files copy_term Term CopyOfTerm CopyOfTerm is an independent copy of Term create mutable 4Datum Mutable Mutable is a new mutable term with current value Datum current_atom Atom One of the currently defined atoms is Atom current input Stream Stream is the current input stream current key KeyName Key Term There is a recorded item in the internal database whose key is Key Term the name of which is KeyName current module Module Module is a module currently in the system current module Module File Module is a module currently in the system loaded from File current op Precedence Type Op Atom Op is an operator type Type precedence Precedence current output Stream Stream is the current output stream current predicate Name Head current predicate Name Head A user defined or library predicate is named Name most general goal Head current stream AbsFileName Mode Stream There is a stream Stream associated with the file AbsFileName and opened in mode Mode debug Switches on debugging in leap mode not available in Runtime Systems debugging Displays debugging status information not available in Runtime Systems dif X Y The terms X and Y are different Summary of Built In Predicates 383 d
217. ave been released by a call to SP free or SP realloc In Muse the blocks are allocated in shared memory Chapter 8 Mixing C and Prolog 141 8 4 Calling Prolog from C In the sequential Development System and in Runtime Systems Prolog and C code may call each other to arbitrary depths The ability to call Prolog from C is not available in the Muse Development System in this release Before calling a predicate from C you must look up the predicate definition by module name and arity The function SP_predicate will return a pointer to this definition or return NULL if the predicate is not visible in the module This definition could be used in more than one call to the same predicate The module specification is optional If NULL or the empty string is given then the default type in module see Section 4 2 Module Spec page 48 is assumed SP_pred_ref SP_predicate char name_string long arity char module_string The function SP_pred may be used as an alternative to the above The only difference is that the name and module arguments are passed as Prolog atoms rather than strings and the module argument is mandatory This saves the cost of looking up the two arguments in the Prolog symbol table This cost dominates the cost of SP_predicate SP_pred_ref SP_pred unsigned long name_atom long arity unsigned long module_atom 8 4 1 Finding One Solution of a Call The easiest way to call a predicate if you are only inter
218. be displayed in the main window and is also used for communicating between applications in Tk Default name is an empty string Chapter 34 Tcl Tk Interface 365 display Display Gives the name of the screen on which to create the main window Default is normally determined by the DISPLAY environment variable tk_main_window TclInterpreter TkWindow Gets a reference to the main window of the application using this interpreter tk make window exist Tk Window This will force a window to be mapped to the screen i e it will force it to show up immediately Normally mapping is delayed as long as possible tk destroy window TkWindow Destroys a window or widget tk num main windows NumberOfWindows Returns the number of main windows currently in use tk do one event tk do one event ListOrBitmask Passes control to Tk for handling a single event This predicate may be called to give Tk time for handling the windows You can specify what events to handle in a List of event flags Alternatively a Bitmask as specified in the Tcl Tk documentation can be used but should be avoided for portability between Tcl Tk versions The flags you can have in List are tk dont wait Don t wait for new events process only events that are ready tk x events tk window events Process window events tk file events Process file events tk timer events Process timer events tk idle events Process Tk DoWhenldle callbac
219. both arguments are constants or variables X4Y Z X 1 Z 6 Y in 1 10 Y 5 no X4Y Z lt gt B X 1 Z 6 Y in 1 10 Y 5 oS 1 Z 6 Y in 1 4 6 10 B in 0 1 Since 1 5 6 holds X Y Z is not interval disentailed although any attempt to make it interval consistent wrt the store results in a contradictory store Chapter 30 Constraint Logic Programming over Finite Domains 285 30 8 Defining Global Constraints 30 8 1 The Global Constraint Programming Interface This section describes a programming interface by means of which new constraints can be written The interface consists of a set of predicates provided by this library module Constraints defined in this way can take arbitrary arguments and may use any constraint solving algorithm provided it makes sense Reification cannot be expressed in this interface instead reification may be achieved by explicitly passing a 0 1 variable to the constraint in question Global constraints have state which may be updated each time the constraint is resumed The state information may be used e g in incremental constraint solving The following two predicates are the principal entrypoints for defining and posting new global constraints clpfd dispatch_global Constraint State0 State Actions A multifile hook predicate telling the solver how to solve constraints of the form Constraint When defining a new constraint a clause of this predic
220. by defining user portray message 2 so as to suppress or alter the format of certain messages These predicates work as follows print message Severity Message Hookable Most messages from the system are printed by calling this predicate Before anything is printed however print message 2 calls user portray message 2 with the same arguments so as to give the user a means of intercepting the message before it is actually printed If user portray_message 2 succeeds nothing is printed otherwise Message is formatted and printed using the default method Message is a term that encodes the message to be printed The format of message terms is subject to change but can be inspected in the file Bips msgs pl of the SICStus Prolog distribution Severity is a term denoting the severity of the message and is one of force Severity Message should be printed without calling the user portray message 2 hook This is useful if user portray message 2 has intercepted the mes sage and now wants to print a reformatted version of it using print message 2 error Message is an uncaught exception The execution will normally be aborted and return to the top level Syntax errors and exceptions that occur while loading files do not necessarily abort the execution however warning Message is a warning e g singleton variables informational Message provides information e g about files being loaded help Message is normally a response to
221. c d a b c d a b c d 27 4 Predicates The following conventions are used in the predicate descriptions below e Mode is either update or read e DBRef is a reference to an open database The reference is returned when the database is opened The reference becomes invalid after the database has been closed e TermRef is a reference to a term in a given database The reference is returned when a term is stored The reference stays valid even after the database is closed and hence can be stored permanently as part of another term A term generally corresponds to several alias references db canonical 2 3 can be used to check whether two TermRefs refer to the same term e Spec is a description of the indexing see the description of db specs below e Term is any Prolog term db open Name Mode DBref db open Name Mode Spec DBref Opens a database with the name Name The database physically consists of a subdi rectory with the same name containing the files that make up the database If the subdirectory does not exist it is created In that case Mode must be update Chapter 27 External Storage of Terms External Database 237 db_open 4 The db spec Spec must be ground if opening a new database If an exist ing database is opened Spec is unified with the db spec given when the database was created If the unification fails the predicate fails and an error is raised db_open 3 On creating a new database the
222. cally linked Produce for each foreign resource a glue code file using 374 SICStus Prolog prepare_foreign_resource ResourceName SourceFile CFile where ResourceName is the name of the resource SourceFile is the Prolog source file containing the resource conversion declarations and CFile is the file where to write the generated code Finally compile and link the glue code files with the user code libraries and the runtime and optionally the development kernel Further information platform specific is provided with the distribution To build a dynamic linked foreign resource Produce a glue code file using prepare_foreign_resource 3 Check the provided platform specific notes for compiler options needed and compile the glue code file and the user code files Likewise check the notes on how a dynamic linked foreign resource is implemented on this platform and link the object files to an appropriate object Chapter 39 Timeout Predicate 375 39 Timeout Predicate The timeout package which may be loaded by the query use_module library timeout contains the predicate time out Goal Time Result The Goal is executed as if by ca11 1 If computing any solution takes more than Time milliseconds process virtual time the goal will fail and Result is unified with the atom time_out If the goal succeeds within the specified time Result is unified with the atom success Time must be a number between not including 0
223. can be used to refer to the constraint later e g for removal findall_constraints Pattern List Unifies List with a list of Constraint 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 314 SICStus Prolog remove constraint 4Id 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 mechanism allows solvers to communicate reductions on the set of possible values of variables prior to making bindings 31 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 see Chapter 5 Load Intro page 51 31 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 b
224. cate C S1 X 52 read as point 51 is con nected by terminal X to point 52 and defined by the single clause 78 SICStus Prolog C XIS X S This predicate is not normally useful in itself it has been given the name upper case c simply to avoid using up a more useful name Then for instance p X gt go to q X stop is translated by p X SO S C SO go S1 C S1 to 82 q X S2 S3 C S3 stop S Extra conditions expressed as explicit procedure calls naturally translate as themselves e g p X gt X finteger X X501 q X translates to p X SO S c SO X 81 integer X X gt 0 q X 1 S Similarly a cut is translated literally Terminals are translated using the built in predicate C S1 X 52 read as point 51 is con nected by terminal X to point 52 and defined by the single clause Terminals on the left hand side of a rule are also translated using C 3 connecting them to the output argument of the head non terminal e g is N not gt aint becomes is N SO S C S0 aint 1 C S not S1 Disjunction has a fairly obvious translation e g args X Y gt dir X to indir Y indir Y dir X translates to Chapter 7 Built In Predicates 79 args X Y SO S dir X SO S1 C S1 to 2 indir Y S2 S indir Y S0 S1 dir X S1 S Similarly for if then if then
225. cate which displays a list of introductory messages initially this list comprises only one message Prolog s but you can add more messages using version 1 This predicate is not available in Runtime Systems version Message Appends Message to the end of the message list which is output by version 0 Message must be an atom This predicate is not available in Runtime Systems The idea of this message list is that as systems are constructed on top of other systems each can add its own identification to the message list Thus version 0 should always indicate which modules make up a particular package It is not possible to remove messages from the list initialization Executes goals defined by initialization 1 Only the first solution is investigated initialization O is called at system re initialization This predicate is not available in Runtime Systems initialization Goal help user help user user Appends Goal to the goal list which is executed by initialization O It is not possible to remove goals from the list This predicate is not available in Runtime Systems initialization 0 1 provide a mechanism which is similar but more general than version 0 1 It can for example be used by systems constructed on top of SICStus Prolog to load their own initialization files Hookable displays basic information or a user defined help message It first calls user user_help 0 and only if that call fails is
226. cates besides the basic out 1 rd 1 and in 1 The in_noblock 1 and rd_noblock 1 does not suspend if the data is not available they fail instead A blocking fetch of a conjunction of data can be done with in 2 or rd 2 Example A simple producer consumer In client 1 producer produce X out p X producer produce X In client 2 consumer in p A consume A consumer consume A Example Synchronization in ready Waits here until someone does out ready t5 Example A critical region 23 in region free wait for region to be free critical part out region free let next one in F 232 SICStus Prolog Example Reading global data rd data Data or without blocking rd_noblock data Data gt do_something Data write Data not available n1 E Example Waiting for one of several events in e 1 e 2 e n E Here is E instantiated to the first tuple that became available F 26 1 Server The server is the process running the blackboard process It is an ordinary SICStus process which can be run on a separate machine if necessary To load the package enter the query use_module library linda server and start the server with linda O or linda 1 linda Starts a Linda server in this SICStus The network address is written to current output stream as Host PortNumber linda Hook Starts a Linda server in this
227. ce linked debugger can display accurate source code lines if the trans formed code needs debugging Layoutl is the layout corresponding to Term1 and Lay out2 should be a valid layout of TermOrTerms see Section 7 1 3 Term I O page 80 For accessing aspects of the load context e g the name of the file being compiled the predicate prolog_load_context 2 see Section 7 6 State Info page 104 can be used user term_expansion 2 4 may also be used to transform queries entered at the terminal in response to the prompt In this case it will be called with Term1 Query and should succeed with TermOrTerms ExpandedQuery goal_expansion Goal Module NewGoal user goal_expansion Goal Module NewGoal A hook predicate This predicate defines transformations on goals while clauses are being consulted compiled or asserted after any processing by user term_ expansion 2 4 of the terms being read in It is called for every simple Goal en countered in the calling context Module If it succeeds Goal is replaced by NewGoal 80 SICStus Prolog otherwise Goal is left unchanged NewGoal may be an arbitrarily complex goal and user goal_expansion 3 is recursively applied to its subgoals This predicate is also used to resolve meta calls to Goal at runtime via the same mech anism If the transformation succeeds NewGoal is simply called instead of Goal Oth erwise if Goal is a goal of an existing predicate that pr
228. ced from Sterling amp Shapiro 86 with permission from the authors file queens pl queens N Qs range 1 N Ns queens Ns Qs queens Qs Qs queens UnplacedQs SafeQs Qs select UnplacedQs UnplacedQs1 Q not attack SafeQs Q queens UnplacedQs1 QlSafeQs Qs not attack Xs X not attack Xs X 1 not attack _ _ not attack Y Ys X N X Y N X Y N Ni is N41 not attack Ys X N1 select X Xs Xs X 42 select Y Ys YlZs X select Ys Zs X range N N N range M N M Ns M N Mi is M41 range M1 N Ns statistics walltime Start findall X queens 10 X L statistics walltime End length L N Time is End Start format d solutions in 3d seconds n SICStus Prolog N Time Note the use of the walltime key i e real elapsed time in the call to statistics 2 The runtime key measures CPU time on the worker that happens to be executing and so normally is not useful Below we show the result of running the queens problem first with 5 workers and then with a single worker In this case the speed up is 3 8 sicstus P SICStus P 3 0 Mon Oct 3 12 44 31 MET 1994 compile queens compiling src sicstus muse V3 examples queens pl yes muse_flag num_workers _ 5 run 724 solutions in 2 760 seconds yes muse_flag num_workers _ 1 ru
229. checks anti monotonicity by requiring that certain variables occurring in the indexical be ground This sufficient condition can sometimes be false for an anti monotone indexical but such situations are rare in practice 30 9 5 FD predicates The following example defines the constraint X Y T as an FD predicate in terms of three index icals Each indexical is a rule responsible for removing values detected as incompatible from one particular constraint argument Indexicals are not Prolog goals thus the example does not express a conjunction However an indexical may make the store contradictory in which case backtracking is triggered plus X Y T X in min T max Y max T min Y Y in min T max X max T min X T in min X min Y max X max Y The above definition contains a single clause used for constraint solving The first indexical wakes up whenever the bounds of S T or S Y are updated and removes from D X S any values that are not compatible with the new bounds of T and Y Note that in the event of holes in the domains of T or Y D X S may contain some values that are incompatible with X Y T but go undetected Like most built in arithmetic constraints the above definition maintains interval consistency which is significantly cheaper to maintain than domain consistency and suffices in most cases The constraint could for example be used as follows X in 1 5 Y in 2 8 plus X Y T X in
230. ckage can be found at http www sics se isl sicstus jasper Package jasper html This documentation will most probably be included in a future version of the manual 176 SICStus Prolog 9 6 Exception Handling Exceptions are handled seamlessly between Java and Prolog This means that exceptions can be thrown in Prolog and caught in Java and the other way around For example if a predicate called from Java raises an exception by raise_exception 1 and the predicate itself does not catch the exception the Java method which performed the query queryCutFail for example will throw an exception containing the exception term Symmetrically a Java exception thrown and not caught in a method called from Prolog will cause the corresponding predicate simple 2 in the example above to raise an exception containing the exception object in the internal Prolog representation of a Java object 9 7 Resources There are almost infinitely many Java resources on the Internet Here is a list of a few which are related to Jasper e The SICStus Prolog Release Notes contains information useful in order to get Jasper working e There is a collection of Java to Prolog examples in library jasper examples See the file README for details on how to use the examples e The main Java resource is Sun s own Java homepage http java sun com e Yahoo http www yahoo com Computers and Internet Programming Languages Java e Information about the
231. command specified by Command The result will be stored as a string list of character codes in Result tcl event TclInterpreter Command Events This call is similar to tcl eval 3 Events is a list of terms stored from Tcl by the prolog event command see Section 34 2 Tcl to Prolog page 363 362 SICStus Prolog 34 1 1 Command Format A Tcl command is specified as follows Command gt Atom other than Number chars PrologString write Term format Fmt Args dq Command br Command sqb Command min Command List OfCommands ListOfCommands List Expr ListExpr Command Command List Expr Command ListOfCommands where Atom Number denote their printed representations chars PrologString denotes the string represented by PrologString a list of character codes write Term denotes the string that is printed by the corresponding built in predicate format Fmt Args denotes the string that is printed by the corresponding built in predicate dq Command denotes the string specified by Command enclosed in double quotes br Command denotes the string specified by Command enclosed in braces sqb Command denotes the string specified by Command enclosed in square brackets min Command denotes the string specified by Command immediately preceded by a hyphen List OfCommands denotes the strings denoted by each element separated by spaces Examples o
232. concept assume that john in the above example has three id cards one stored in his sportsman prototype identifying the club he is member of one stored in his professor prototype identifying the university he works in and finally one stored locally identifying his social security number Given the following methods in the object john mi X super lt id_card X amp m2 X super S S lt id_card X amp one may ask the following john m1 X will follow the default inheritance and returns X johns club john m2 X will backtrack through the possible supers returning X johns_club X johns university 32 4 6 Semantic Links to Other Objects Some object oriented languages have syntactic constructs for redirecting the inheritance chain for certain methods to completely other objects which are not defined in the object s inheritance hierarchy This is not needed in Prolog Objects due to delegation Assume that the method m n is linked to object some object we just add a method for this m X1 Xn some object lt m X1 Xn amp 32 4 7 Dynamically Declared Objects When an object is declared and compiled into Prolog Objects its methods cannot be changed during execution Such an object is said to be static To be able to update any method in an object the object has to be declared dynamic There is one exception the inheritance hierarchy declared by super 1 2 cannot b
233. 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 disjunctions are allowed in the guard 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 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 th
234. constraint it suffices for the definition to contain a single clause for solving the constraint If a constraint is reified or occurs in a propositional formula the definition must contain four clauses for solving and checking entailment of the constraint and its negation The role of each clause is reflected in the neck operator The following table summarizes the different forms of indexical clauses corresponding to a constraint C In all cases Head should be a compound term with all arguments being distinct variables Head Indexicals The clause consists of propagating indexicals for solving C Head Indexicals The clause consists of propagating indexicals for solving the negation of C Head Indexical The clause consists of a single checking indexical for testing entailment of C Head Indexical The clause consists of a single checking indexical for testing entailment of the negation of C When a constraint is reified the solver spawns two reactive agents corresponding to detecting entailment and disentailment Eventually one of them will succeed in this and consequently will bind B to 0 or 1 A third agent is spawned waiting for B to become assigned at which time the constraint or its negation is posted In the mean time the constraint may have been detected as dis entailed in which case the third agent is dismissed The waiting is implemented by means of the coroutining facilities of SICStus Prolog As an ex
235. cribed in this section were introduced in early implementations of Prolog to provide efficient means of performing operations on large quantities of data The introduction of indexed dynamic predicates have rendered these predicates obsolete and the sole purpose of providing them is to support existing code There is no reason whatsoever to use them in new code These predicates store arbitrary terms in the database without interfering with the clauses which make up the program The terms which are stored in this way can subsequently be retrieved via the key on which they were stored Many terms may be stored on the same key and they can be individually accessed by pattern matching Alternatively access can be achieved via a special identifier which uniquely identifies each recorded term and which is returned when the term is stored 116 SICStus Prolog recorded Key Term Ref The internal database is searched for terms recorded under the key Key These terms are successively unified with Term in the order they occur in the database At the same time Ref is unified with the implementation defined identifier uniquely identifying the recorded item If the key is instantiated to a compound term only its principal functor is significant If the key is uninstantiated all terms in the database are successively unified with Term in the order they occur recorda Key Term Ref The term Term is recorded in the internal database as the first i
236. cstus ini and 96 consults it if it exists 96 e ensures a file File is loaded if 1 File was supplied as program arguments e calls initialization O to run user defined initializations In recursive calls to Prolog from C this predicate will return back to C instead In Muse will adjust the system to one worker garbage collect Performs a garbage collection of the global stack immediately garbage collect atoms Performs a garbage collection of the atoms immediately gc Enables garbage collection of the global stack the default nogc Disables garbage collection of the global stack prompt Old New The sequence of characters prompt which indicates that the system is waiting for user input is represented as an atom and unified with Old the atom bound to New specifies the new prompt In particular the goal prompt X X unifies the current prompt with X without changing it Note that this predicate only affects the prompt given when a user s program is trying to read from the standard input stream e g by calling read 1 Note also that the prompt is reset to the default on return to top level 126 version SICStus Prolog Displays the introductory messages for all the component parts of the current system Prolog will display its own introductory message when initially run and on reinitial ization by calling version O If this message is required at some other time it can be obtained using this predi
237. ct Type where Object is the object identifier and Type is either static or dynamic If the type is static the other generated predicates will be static otherwise they will be dynamic 32 9 5 The Method Code Each method clause translates to a Prolog clause with two extra arguments Self a variable and Myself The latter argument is needed to cater for passing object parameters to the method body which is desribed further in next section The method body is translated to a Prolog clause body as follows The code is traversed and the goals are transformed according to the following transformation patterns and rules In the transformation rules the notation Msg X Y denotes the term produced by augmenting Msg by the two arguments X and Y Goal where Goal is a variable is translated to objects call_from_body Goal Self Myself Src where Src is the source module objects call_from_body 4 will meta interpret Goal at runtime Msg is translated to Myself Msg Myself Myself if Msg is a non variable Otherwise it is translated to objects call object Myself Msg Myself Msg is translated to Myself Msg Self Myself if Msg is a non variable Otherwise it is translated to objects call object Myself Msg Self super Msg is translated to objects call super exp Myself Msg Super Myself Super if Msg is a non vari able call super exp 3 searches the supers of Myself Super is bound to the super object where t
238. ctions are in file ObjectFile Obsolete use foreign resource 2 instead foreign resource ResourceName Functions A hook predicate tells Prolog that foreign functions Functions are in resource Re sourceName 384 SICStus Prolog format Format Arguments format Stream Format Arguments Writes Arguments according to Format on the stream Stream or on the current output stream freeze Var Goal Blocks Goal until nonvar Var holds frozen Var Goal The goal Goal is blocked on the variable Var functor Term Name Arity functor Term Name Arity The principal functor of the term Term has name Name and arity Arity garbage_collect Performs a garbage collection of the global stack garbage_collect_atoms Performs a garbage collection of the atoms gc Enables garbage collection of the global stack get C get Stream C The next printing character from the stream Stream or from the current input stream is C get0 C get0 Stream C The next character from the stream Stream or from the current input stream is C get mutable Datum Mutable The current value of the mutable term Mutable is Datum goal_expansion Goal Module NewGoal user goal_expansion Goal Module NewGoal A hook predicate Defines a transformation from Goal in module Module to NewGoal ground X X is currently free of unbound variables halt Halts Prolog returns to C in recursive calls to Prolog from
239. cure state and the last stored term is safe even if the SICStus process dies machine rebooted process killed halt 0 power failure but see Section 27 2 Current Limitations page 235 27 2 Current Limitations e Only one process can open the same database e The terms are not necessarily fetched in the same order as they were stored e If the process dies during the db store the database could be inconsistent e At the user s option a database can be operated in an insecure state where modified pages are not immediately flushed to disk This is useful e g when a database is created by storing a large number of terms See db_buffering 2 3 236 SICStus Prolog 27 3 The DB Spec Informal Description The db spec defines which parts of a term that is used for indexing in a database It is a structure with the functor on or off The arguments are on off or the same kind of structure The db spec is compared with the indexed term and every argument where there is an on in the db spec is indexed If the db spec is of lower arity than the indexed term the last part of the indexed term is skipped or vice versa The idea of a db spec are illustrated with a few examples A section further down explains the db spec in a more formal way DB Spec Term the parts with indexing are underlined on on a b a b c a a b c d as Prolog on on on a b a b c a b c d a b c d a b c d on off on on a b a b c a b
240. d 5 2 4 Block Declarations The declaration block BlockSpec BlockSpec where each BlockSpec is a mode spec specifies conditions for blocking goals of the predicate referred to by the mode spec 3 say When a goal for 3 is to be executed the mode specs are interpreted as conditions for blocking the goal and if at least one condition evaluates to true the goal is blocked A block condition evaluates to true iff all arguments specified as are uninstantiated in which case the goal is blocked until at least one of those variables is instantiated If several conditions evaluate to true the implementation picks one of them and blocks the goal accordingly The recommended style is to write the block declarations in front of the source code of the predicate they refer to Indeed they are part of the source code of the predicate and must precede the first clause For example with the definition block merge merge merge Y Y merge X X merge H X EIY HIZ merge H X EIY EIZ E merge X EIY Z H 5 H E merge H X Y Z lt gt calls to merge 3 having uninstantiated arguments in the first and third position or in the second and third position will suspend The behavior of blocking goals for a given predicate on uninstantiated arguments cannot be switched off except by abolishing or redefining the predicate Block declarations general
241. d Defaults to sicstus 3 7 Note that the spaces are significant prolog use sicstus sd Set to t to enable the source linked debugging extensions by default Defaults to nil The debugging can be enabled via the Prolog menu even if this variable is nil Note that the source linked debugging only works if prolog system version is set correctly pltrace port arrow assoc Only relevant for source linked debugging this controls how the various ports of invo cation boxes see Section 6 1 Procedure Box page 59 map to arrows that point into the current line of code in source code buffers Initialized as 2 call gt gt gt exit t W444 ndexit nU redo e lt lt lt fail 1 8 exception a zz5 where ndexit is the non deterministic variant of the Exit port prolog indent width How many positions to indent the body of a clause Defaults to tab width normally 8 prolog paren indent The number of positions to indent code inside grouping parentheses Defaults to 4 which gives the following indentation P ql gt q2 q3 Note that the spaces between the parentheses and the code are automatically inserted when TAB is pressed at those positions Chapter 1 How to Run Prolog 23 prolog align comments flag Set to nil to prevent single 4 comments to be automatically aligned Defaults to t Note that comments with one are indented to comment column comments with two to the code leve
242. d In fact this is the only situation where expansion can be applied with relative safety To see this consider what happens when the top level evaluates the expansion namely some calls to the clp Q R solver followed by the call of the purified query As we learned in Section 29 2 3 Feedback page 253 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 compiling files needing expansion with expand 0 and noexpand 0 29 7 1 Monash Examples This collection of examples has been 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 In order to execute the examples a small compatibility package has to be loaded first clp r use module library clpqr monash Then assuming you are using clp R clp r expand library clpqr examples monash rkf45 noexpand clp r go Point 0 00000 0 75000 0 00000 Point 0 50000 0 61969 0 47793 Point 1 00000 0 29417 0 81233 Point 1 50000 0 10556 0 95809 Chapter 29 Constraint Logic Programming over Rationals or Reals 267 Point 2 00000 0 49076 0 93977 Point 2 50000 0 81440 0 79929 Point 3 00000 1 05440 0 57522 Iteration finished 439 derivative evaluations 29 7 1 1 Compatibility Notes Th
243. d Y are sufficiently instantiated It is defined as if by dif X Y when X Y X Y call residue Goal Residue The Goal is executed as if by call 1 If after the execution there are still some subgoals of Goal that are blocked on some variables then Residue is unified with a list of VariableSet Goal pairs and those subgoals are no longer blocked on any variables Otherwise Residue is unified with the empty list VariableSet is a set of variables such that when any of the variables is bound Goal gets unblocked Usually a goal is blocked on a single variable in which case VariableSet is a singleton Goal is an ordinary goal sometimes module prefixed For example call residue dif X f Y X Z Res X f 2 Res Y Z prolog dif f 2 f 7 14 Debugging Debugging predicates are not available in Runtime Systems unknown OldState NewState OldState is the current state of the Action on unknown predicates flag and sets the flag to NewState This flag determines whether or not the system is to catch calls to undefined predicates see Section 1 6 Undefined Predicates page 15 when user unknown predicate handler 3 cannot handle the goal The possible states of the flag are trace Causes calls to undefined predicates to be reported and the debugger to be entered at the earliest opportunity fail Causes calls to such predicates to fail error Causes calls to such predicates t
244. d bound search a dynamic variable ordering using the first fail principle and domain splitting exploring the upper part of domains first use 282 SICStus Prolog constraints Variables Cost labeling ff bisect down minimize Cost Variables As opposed to the predicates above which search for consistent assignments to domain variables the following predicate searches for a consistent ordering among tasks competing for an exclusive resource without necessarily fixing their start times order_resource Options Resource where Options is a list of search options and Resource represents a resource as returned by serialized_resource 3 see Section 30 3 4 Combinatorial Constraints page 277 on which tasks must be serialized True if a total ordering can be imposed on the tasks enumerating all such orderings via backtracking The search options control the construction of the total ordering It may contain at most one of the following atoms selecting a strategy first The ordering is built by repetitively selecting some task to be placed before all others last The ordering is built by repetitively selecting some task to be placed after all others and at most one of the following atoms controlling which task to select at each step If first is chosen the default the task with the smallest value is selected otherwise the task with the greatest value is selected est The tasks are ordered by earliest start time lst T
245. d to a Prolog term Prolog object Java SPTerm M The Java method should return an object of class SPTerm which will be converted to the internal Prolog representation of a Java object Prolog atom Java SPTerm M The Java method should return an object of class SPTerm which will be converted to a Prolog atom Prolog boolean Java boolean M The Java should return boolean The value will be converted to a Prolog atom in true false Prolog chars Java String M The Java method should return an object of class String which will be converted to a list of character codes Prolog string Java String MO The Java method should return an object of class String which will be converted to an atom 172 SICStus Prolog 9 3 1 Calling Java from Prolog An Example The following is an simple but complete example of how a Java method can be called from Prolog First we must write the resource file Let us call it simple pl File simple pl module simple simple 2 use module library jasper load foreign resource simple foreign method Simple simpleMethod static java simple integer integer foreign_resource simple method Simple simpleMethod static 1 This file is the processed with the script splfr see Section 8 2 5 Interface Predicates page 133 to produce a foreign resource splfr simple simple pl SICStus 3 7
246. d variables created during the execution of Goal are located For each such variable attribute goal 2 produces a term representing the constraint encoded by the attribute and Residue is unified with the list of all such terms The exact definition of project attributes 2 is constraint system dependent but see Section 29 5 Projection page 259 for details about projection in clp Q R In the following example we sketch the implementation of a finite domain solver Note that an industrial strength solver would have to provide a wider range of functionality and that it quite likely would utilize a more efficient representation for the domains proper The module exports a single predicate domain Var Domain which associates Domain a list of terms with Var A variable can be queried for its domain by leaving Domain unbound We do not present here a definition for project attributes 2 Projecting finite domain con straints happens to be difficult module domain domain 2 use module library atts use module library ordsets ord intersection 3 ord intersect 2 list to ord set 2 D attribute dom 1 196 verify_attributes Var Other Goals get_atts Var dom Da var Other gt 23 23 get atts Other dom Db gt ord intersection Da Db Dc Dc El Els Els gt Goals Other E1 4 Goals put_atts Other dom Dc Goals put atts ther do
247. db spec is on on the same kind of indexing as in the internal database When opening an existing database any db spec from the database is accepted db_close db_close DBref Closes a database db c1ose 0 closes the default database Note that after db c1ose O there is no default database abort 0 does not close databases set default db DBref set default db Namoe Sets the database Name or DBref to be the default database regardless of whether there already is one or not get default db DBref Unifies DBref with the default database current db Name Mode Spec DBref Unifies the arguments with the open databases This predicate can be used for enu merating all currently open databases through backtracking db store Term TermRef db store DBref Term TermRef Stores Term in the database DBref which defaults to the default database TermRef is unified with a corresponding term reference db fetch Term TermRef db fetch DBref Term TermRef Unifies Term with a term from the database DBref which defaults to the default database At the same time TermRef is unified with a corresponding term reference Backtracking over the predicate unifies with all terms matching Term If you simply want to find all matching terms it is more efficient to use db findall 2 3 If TermRef and DBref are instantiated and the referenced term is not erased the referenced term is read and unified with Term
248. defined meta predicate declarations as indicated by the mode specs in this manual e g call Term Chapter 5 Loading Programs 51 5 Loading Programs Programs can be loaded in three different ways consulted or compiled from source file or loaded from object files The latter is the fastest way of loading programs but of course requires that the programs have been compiled to object files first Object files may be handy when developing large applications consisting of many source files but are not strictly necessary since it is possible to save and restore entire execution states see Section 7 17 Misc Pred page 124 Consulted or interpreted predicates are equivalent to but slower than compiled ones Although they use different representations the two types of predicates can call each other freely The SICStus Prolog compiler produces compact and efficient code running about 8 times faster than consulted code and requiring much less runtime storage Compiled Prolog programs are comparable in efficiency with LISP programs for the same task However against this compilation itself takes about twice as long as consulting and tracing of goals that compile in line are not available in compiled code The compiler operates in three different modes controlled by the Compilation mode flag see prolog_flag 3 The possible states of the flag are compactcode Compilation produces byte coded abstract instructions This is the de
249. ding the new domain constraint X S R to the store where S R denotes the value of R in S When a checking indexical fires it checks if D X S is contained in S R and if so the constraint corresponding to the indexical is detected as entailed 30 9 2 Range Expressions A range expression has one of the following forms where Ri denote range expressions Ti denote integer valued term expressions S Ti denotes the integer value of Ti in S X denotes a variable I denotes an integer and S denotes the current store dom X evaluates to D X S T1 Tn evaluates to S T1 S Tn Any term expression containing a subexpression which is a variable that is not quantified by unionof 3 will only be evaluated when this variable has been assigned T1 T2 evaluates to the interval between S T1 and S T2 RI AR2 evaluates to the intersection of S R1 and S R2 RIN R2 evaluates to the union of S R1 and S R2 R2 evaluates to the complement of S R2 R1 R2 R1 T2 evaluates to S R2 or S T2 added pointwise to S R1 R2 evaluates to S R2 negated pointwise R1 R2 R1 T2 T1 H2 evaluates to S R2 or S T2 subtracted pointwise from S R1 or S T1 R1 mod R2 R1 mod T2 evaluates to S R1 pointwise modulo S R2 or S T2 R1 R2 evaluates to S R2 if S R1 is a non empty set otherwise evaluates to the empty set This expression is commonly used in the context R1 inf sup M R3 which evaluates to S R3 if S R1 is an empty set
250. e Chapter 7 Built In Predicates 77 expr Z gt term X expr Y Z is X Y expr Z gt term X expr Y Z is X Y expr X gt term X term Z gt number X x term Y Z is term Z number X term Y Z is term Z number Z number C gt number C number C gt number X C is X number X gt C O 2 C C lt 9 X is C O In the last rule C is the character code of some digit The query expr Z 2 3 5 1 will compute Z 14 The two extra arguments are explained below Now in fact grammar rules are merely a convenient syntactic sugar for ordinary Prolog clauses Each grammar rule takes an input string analyses some initial portion and produces the remaining portion possibly enlarged as output for further analysis The arguments required for the input and output strings are not written explicitly in a grammar rule but the syntax implicitly defines them We now show how to translate grammar rules into ordinary clauses by making explicit the extra arguments A rule such as p X gt q X translates into p X SO S q X SO S If there is more than one non terminal on the right hand side as in p X Y BI q X r x Y s Y then corresponding input and output arguments are identified as in p X Y SO S q X S0 S1 r X Y S1 2 r Y S2 S Terminals are translated using the built in predi
251. e Predicates that expect the name of a Prolog source file as an argument use absolute_file_name 2 see Section 7 1 5 Stream Pred page 89 to look up the file This predicate will first search for a file with the suffix p1 added to the name given as an argument If this fails it will look for a file with no extra suffix added There is also support for libraries In general this directive can be any list of filenames such as myprog extras tests In this case all three files would be consulted The clauses for all the predicates in the consulted files will replace any existing clauses for those predicates i e any such previously existing clauses in the database will be deleted Note that consult 1 in SICStus Prolog behaves like reconsult 1 in DEC 10 Prolog 12 SICStus Prolog 1 3 Inserting Clauses at the Terminal Clauses may also be typed in directly at the terminal although this is only recommended if the clauses will not be needed permanently and are few in number To enter clauses at the terminal you must give the special directive user and the new prompt shows that the system is now in a state where it expects input of clauses or directives To return to top level type D The system responds thus user consulted 20 msec 200 bytes 1 4 Directives Queries and Commands Directives are either queries or commands Both are ways of directing the system to execute some goal or goals In
252. e denotes the start of an escape sequence with special meaning see Escape Sequences page 401 2 1 1 2 Floats Constants also include floats such as 1 0 3 141 4 5E7 0 12e 8 12 0e 9 Note that there must be a decimal point in floats written with an exponent and that there must be at least one digit before and after the decimal point 28 SICStus Prolog 2 1 1 3 Atoms Constants also include atoms such as a void gt A1go1 68 1 Constants are definite elementary objects and correspond to proper nouns in natural language For reference purposes here is a list of the possible forms which an atom may take 1 Any sequence of alphanumeric characters including _ starting with a lower case letter 2 Any sequence from the following set of characters X lt gt 70H 8 This set can in fact be larger see Token String page 398 for a precise definition 3 Any sequence of characters delimited by single quotes If the single quote character is included in the sequence it must be written twice e g can t Backslashes in the sequence denote escape sequences see Escape Sequences page 401 4 Any of 1 47 Note that the bracket pairs are special and are atoms but and are not However when they are used as functors see below the form X is allowed as an alternative to X The form X is the normal notation for lists as an alternative to X 1 2 1 1 4 Variables Variables
253. e 235 2l Basis RM ER e eU de e cea ed 235 27 2 Current Limitations 0 0 cee eee eee hn 235 27 3 The DB Spec Informal Description 02 045 236 21 4 Predicas tee ee A RS ane ES 236 27 5 An Example Session 0 0 0 c cece eee eee nen 238 21 0 T he Db Spec uud es nuit A a Linas RERUM 239 28 Boolean Constraint Solver 241 28 1 Solver Interface zi xz e sete t ot ra ARR E adc pnto 242 28 2 Examples urere er m reto aedi od POSUER ne EO RU 242 28 2 1 Example tt e Dx tte ea e CARA R 242 28 2 2 Example Zi BAG PERI Hi ee 243 28 23 Eixample 3e em aV eae t M eR 243 28 24 Example diia er eret e e pex eu 244 29 Constraint Logic Programming over Rationals or Ieri rc 247 20 1 Introductions i eve RR CRT er PERRA d 247 Referencing this Software 247 Acknowledgments eeeeeeeeee e ete e nent n eee eens 247 29 2 Solver Interface consorcio 248 Notational Conventions 0 000 eee e eee eee eee ene 248 29 2 1 Solver Predicates ge ih pee erie E da 248 20 22 JUnificatlon scie ime Ra EN iw eee de 252 29 2 3 Feedback and Bindings sseeeesseeeeuus 253 29 3 Linearity and Nonlinear Residues 0000 eee eee eee 253 29 3 1 How Nonlinear Residues are made to disappear 254 29 3 2 Isolation Axioms ssseeeeesee en 254 29 4 Numerical Precision and Rationals oo ooocoooo 255 29 5 Projection and Redundancy El
254. e Monash examples have been written for clp R Nevertheless all but rkf45 complete nicely in clp Q With rkf45 clp Q runs out of memory This is an instance of the problem discussed in Section 29 4 Numerical Precision page 255 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 top level clp r expand library clpqr examples monash mortgage noexpand go2 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 clp r mg 999 3 Int O 400 dump clpr _B _B Int _A 400 0 0 0 clpr _A _A Int 400 0 0 0 _B 599 0 999 0 Int 268 SICStus Prolog 29 8 A Mixed Integer Linear Optimization Example The predicates bb_inf 3 bb_inf 5 implement a simple Branch and Bound search algorithm for Mixed Integer Linear MIP Optimization examples Serious MIP is not trivial The implemen tation library Cclpqr bb pl is to be understood as a starting point for more a
255. e R Color super ellipse R R Color Ts red_circle R super circle R red and their expansions ellipse _ _ _ so_type ellipse _ _ _ static ellipse _ _ _ area A _ B B fix param ellipse C D _ B user A is C D 3 14159265 ellipse _ _ _ color A _ B B fix_param ellipse _ _ A B ellipse _ _ _ fix_param ellipse B C D A objects object_class ellipse B C D A circle _ _ so_type circle _ _ static Chapter 32 Prolog Objects 349 circle _ _ super ellipse A A B _ circle A B circle _ _ fix_param circle B C A objects object_class circle B C A circle _ _ fix_param ellipse B B C A objects object_class circle B C A red_circle _ so_type red_circle _ static red_circle _ super circle A red _ red_circle A red_circle _ fix_param red circle B A objects object_class red_circle B A red circle fix param circle B red A objects object_class red_circle B A red circle fix param ellipse B B red A objects object class red circle B A The second additional argument contains the receiver of a method call If the method makes use of any parameter of the object where it is defined it places a call to the reserved predicate fix_ param 2 in the module of the receiver The purpose of this call is to bind the parameters used
256. e aa a aes 236 ADLER ugue wees EPSE E eda 236 db Store 4245 0 5 help id ad NE 237 db store 3 cv br ot v ber UR 237 debug 0 c asiee ee Sav EErEE EE eee bev oe era re one 61 120 debugger print options prolog flag 108 debugging debugger command 67 debugging prolog flag 0 0008 105 debugging 0 ind Rip ee is ee 62 121 412 deep fails profile_data 4 option 122 del assoc 4u u uou Mou ote VEM eh ees 192 del edg s 3 orinal pr nd 222 226 del_max_assoc 4 0 cece eee eee 192 delunin assoc 4 c i bona irn 192 del vertices 3 geni nobel peu ides 221 226 delete Sinks aussi qu PR tees tp ope vp 201 delete till diia dd RED PREX AGE er 215 delete file 2 ER UWsgkde Su EVI E Ed 215 delete from heap 4 sierota re ela sa a 200 TO 120 directory files 2 isses 215 display debugger command sssses 66 display Linares 82 A O 276 domain_error 4 error class 103 a vs cei eel tak ean RISE T EE Ede 251 dynamic 1 declaration esses 54 E edges 2 t acad une Een s bed 221 225 Clement A Pearse pagan terns 277 Empty ASEO Leica dt iba du 191 empty fdset Luciana sa enr a 287 eupty heap 1i sresuetecegUpLP UU Looe eae 199 empty interval 25 023 vere RR are Eri e 287 empty queue T reio hides e A inde VERAS 211 ensure loaded 1 sess sess aa 53 75 entailed li iid vede wedded r Rb pup hir 249 enviton
257. e 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 n inequality constraints between each pair of different variables However the extreme case of having a single constraint modeling the whole constraint 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
258. e called methods So an object is conceptually a named collection of methods and attributes Some of the methods defined for an object need not be stored explicitly within the object but are rather shared with other objects by the inheritance mechanism The Object system allows objects to be defined in a file or dynamically created during the execution of a program Objects defined in a file are integrated into SICStus Prolog in a way similar to definite clause grammars That is to say objects have a specific syntax as Prolog terms and can be loaded and expanded into Prolog code When an object is created during load time or run time it inherits the methods and attributes of its prototypical object s Objects defined in a file can be either static or dynamic Also methods can be either dynamic or static these properties are inherited by sub objects Objects created during execution are dynamic The inheritance mechanism is implemented using the importation mechanism of the module system The default inheritance is an inheritance by overriding mechanism which means that if a method is defined locally and the same method is defined in a super object then the clauses of the super method are not part of the definition of the local one As usual in Prolog methods can be non determinately defined and alternative answers can be retrieved through backtracking Using the delegation mechanism other methods for knowledge sharing can be implemented b
259. e changed By including the fact dynamic as part of the object body the object becomes dynamic Chapter 32 Prolog Objects 337 dynamic object dynamic amp 32 4 8 Dynamic Methods To be able to change a method with functor F and arity N in a static object the method has to be declared dynamic by storing the following fact in the object some_object dynamic F N amp js Each book in a library can be represented as an object in which the name of the book is stored the authors and a borrowing history indicating when a book is borrowed and when it is returned A history item may have the form history item Person Status Date where Status is either borrowed or returned and Date has the form Y Y MM DD for YY year MM month DD day A typical book book 12 could have the following status Note that history item 3 is dynamic book 12 4 super book amp title The Art of Prolog authors Leon Sterling Ehud Shapiro dynamic history_item 3 amp history_item Dan Sahlin returned 92 01 10 amp history_item Dan Sahlin borrowed 91 06 10 amp Dynamic methods that are stored in an object can be updated as in usual Prolog programs by sending assert and retract messages directly to the object For example to borrow a book the following method could be defined in the object book We assume that the top most history_item fact is the latest transaction and there is
260. e de structive assignment In other words any destructive assignments are transparently undone on backtracking Modifications that are intended to survive backtracking must be done by assert ing or retracting dynamic program clauses instead Unlike previous releases of SICStus Prolog destructive assignment of arbitrary terms is not allowed A mutable term is represented as a compound terms with a reserved functor mutable Value Timestamp where Value is the current value and Timestamp is reserved for bookkeeping purposes Any copy of a mutable term created by copy_term 2 assert retract an internal database predicate or an all solutions predicate is an independent copy of the original mutable term Any destructive assignment done to one of the copies will not affect the other copy The following operations are provided create_mutable Datum Mutable Mutable is a new mutable term with initial value Datum Datum must not be an unbound variable get_mutable Datum Mutable Datum is the current value of the mutable term Mutable update_mutable Datum Mutable Updates the current value of the mutable term Mutable to become Datum Datum must not be an unbound variable is_mutable Mutable Checks that Mutable is currently instantiated to a mutable term see Section 7 8 Mod ify Term page 113 7 9 Modification of the Program The predicates defined in this section allow modification of dynamic predicates Dynamic c
261. e 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 gt F A_N_M_ 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 Chapter 31 Constraint Handling Rules prime 1_1_0 3 prime 1_2 2 primes 1 primes 1_1 2 verify_attributes 3 315 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 eratosthenes constraints primes 1 prime 1 31 3 10 Operator Declarations This table lists the operators as used by the CHR library 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 op 1100 xfx op 1100 xfx op 1050 xfx amp op 500 yfx 31 3 11 Exceptions The CHR runtime system reports instantiation and type errors for the predicates find co
262. e from predicate P to predicate Q if P calls Q and Q is not a built in predicate xref Files Files is a single file or a list of files as accepted by consult 1 and friends The predicate prints on the current output stream a list of predicates which are reachable from use in the call graph but not defined followed by a list of predicates which are defined but not reachable from use There may be references not found by xref because of the dynamic nature of the Prolog language Note that xref does not consider a predicate used unless it is reachable from a directive an export list or a public declaration In non module files it is therefore recommended that the entry point predicates be declared as public Predicates reached by meta calls only may also have to be declared public to be considered used If a module file file containing a module declaration is encountered the module specified is used for that file and subsequent files up to the next module file This enables packages consisting of several files which are to be loaded in the same module to be correctly treated The type in module is the default module 378 SICStus Prolog Summary of Built In Predicates 379 Summary of Built In Predicates Commits to any choices taken in the current predicate P Q P and Q Head Body Not a built in predicate reserved syntax for grammar rules P gt Q R If P then Q else R using first solution of P only
263. e of some queries is shown below where a number preceded by _ is a system generated name for a variable member X tom dick harry X tom X dick X harry no member X a b f Y c member X f b Z d X f b c Y b Z c yes member X f _ g X f _A yes Commands are like queries except that 1 Variable bindings are not displayed if and when the command succeeds 2 You are not given the chance to backtrack through other solutions 1 4 2 Commands Commands start with the symbol Any required output must be programmed explicitly e g the command 14 SICStus Prolog member 3 1 2 3 write ok directs the system to check whether 3 belongs to the list 1 2 3 Execution of a command terminates when all the goals in the command have been successfully executed Other alternative solutions are not sought If no solution can be found the system prints Warning Goal goal failed as a warning The principal use for commands as opposed to queries is to allow files to contain directives which call various predicates but for which you do not want to have the answers printed out In such cases you only want to call the predicates for their effect i e you don t want terminal interaction in the middle of consulting the file A useful example would be the use of a directive in a file which consults a whole list of other files e g bits bobs main te
264. e of the values allowed for the syntax errors Prolog flag The default is set by that flag variable names 7Names Names is bound to a list of Name Var pairs where each Name is an atom indicating the name of a non anonymous variable in the term and Var is the corresponding variable singletons Names Names is bound to a list of Name Var pairs one for each variable appear ing only once in the term and whose name does not begin with _ cycles Boolean Boolean must be true or false If selected any occurrences of 0 2 in the term read in are replaced by the potentially cyclic terms they denote as described above Otherwise the default Term is just unified with the term read in layout Layout Layout is bound to a layout term corresponding to Term The layout Y of a term X is one of e If X is a variable or atomic term Y is the number of the line where X occurs e If X is a compound term Y is a list whose head is the number of the line where the first token of X occurs and whose remaining elements are the layouts of the arguments of X e if no line number information is available for X read term T layout L variable names Va singletons S I foo X X Y IE L 35 36 36 36 37 37 37 3811 S Y 2 A T foo B B A Va X2 B Y A 82 SICStus Prolog write Term ISO write Stream Term ISO The term Term is written onto Stream according to current o
265. e 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 31 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 31 4 5 CHR Debugging Options page 320 In particular you can just type CR 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 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
266. e shared constraint are together in one module Changes may be necessary like strengthening guards to avoid divergence or loops in the computation 324 SICStus Prolog 31 6 Constraint Handlers The CHR library comes with plenty of constraint handlers written in CHR arc pl classical arc consistency over finite domains bool 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 over integers and reals with arithmetic functions 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 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 elimination for equations with Fourier s algorithm for inequations several variations possible 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 orderin
267. eam is the current output stream The current output stream is also accessed by the C variable SP curout current stream FileName Mode Stream Stream is a stream which was opened in mode Mode and which is connected to the absolute file name Filename an atom or to the file descriptor Filename an inte ger This predicate can be used for enumerating all currently open streams through backtracking Chapter 7 Built In Predicates 91 set input Stream ISO Sets the current input stream to Stream set output Stream ISO Sets the current output stream to Stream flush output ISO flush output Stream ISO Flushes all internally buffered characters for Stream to the operating system open null stream Stream Opens an output stream Everything written to this stream will be thrown away character count Stream N N is the number of characters read written on stream Stream line count Stream N N is the number of lines read written on stream Stream line position 4Stream N N is the number of characters read written on the current line of Stream Stream position 4Stream Position Position is a term representing the current position of Stream The relative order of stream position terms can be tested with standard term comparison predicates such as compare 3 but you should not otherwise rely on their internal representation This operation is available for any Prolog stream set stream positio
268. eceiving modules a warning is issued and the importation is canceled In the first case redefinition silently takes place if the flag redefine warnings has the value off see prolog flag 3 The binding of an imported predicate remains even if the origin is reloaded or deleted However abolish 1 breaks up the importation binding When a module file is reloaded a check is made that the predicates imported by other modules are still in the public list If that is not the case a warning is issued Note that an imported predicate may be re exported 4 5 Module Name Expansion Some predicates take goals as arguments i e meta predicates These arguments must include a module specification stating which module the goal refers Some other predicates also need module information i e compile 1 The property of needing module information is declared with a meta predicate declaration see Section 4 6 Meta Decl page 50 Goals for these predicates are module name expanded to ensure the module information Goals issued at top level and goals appearing as directives are expanded prior to execution while goals in the bodies of clauses are expanded at compile time The expansion is made by preceding the relevant argument with Module If the goal is prefixed by Module Module is used for the expansion otherwise the source type in module is used n argument is not expanded if 1 It already has a module prefix 2 It is a variable which appears i
269. eclarations for example Constraint identifiers must be distinct variables not occurring elsewhere in the heads 310 SICStus Prolog 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 Headsi Body However the simpagation rule is more compact to write more efficient to execute and has better termination behavior than the corresponding simplification rule since the constraints comprising Heads1 will not be removed and inserted again 31 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 in
270. ected Via To Path Via Visited connection Stockholm Katrineholm connection Stockholm Vasteras connection Stockholm Uppsala connection Uppsala Vasteras connection Katrineholm Hallsberg connection Katrineholm Linkoping connection Hallsberg Kumla connection Hallsberg Goteborg connection Orebro Vasteras connection Orebro Kumla not_visited _ not visited X Visited Y X Y not visited Visited Y train c include lt stdio h gt include lt sicstus sicstus h gt void write_path SP_term_ref path char text NULL SP_term_ref tail SP_new_term_ref via SP_new_term_ref SP_put_term tail path while SP_get_list tail via tail 158 SICStus Prolog if text printf gt SP_get_string via amp text printf s text printf n int main int argc char argv int rval SP_pred_ref pred SP_qid goal SP_term_ref from to path Initialize Prolog engine This call looks up SP_PATH in order to find the Runtime Library if SP FAILURE SP initialize argc argv NULL 1 fprintf stderr SP initialize failed s n SP error message SP errno exit 1 rval SP_restore train sav if rval SP_ERROR rval SP_FAILURE 1 fprintf stderr Could not restore train sav n exit 1 L
271. edence of is such that it dominates but is dominated by An example is the clause grandfather X 2 mother X Y father X Y father Y Z which can be read as For any X Y and Z X has Z as a grandfather if either the mother of X is Y or the father of X is Y and the father of Y is Z Such uses of disjunction can always be eliminated by defining an extra predicate for instance the previous example is equivalent to grandfather X Z parent X Y father Y Z parent X Y mother X Y parent X Y father X Y and so disjunction will not be mentioned further in the following more formal description of the semantics of clauses Chapter 2 The Prolog Language 33 The token when used outside a list is an alias for The aliasing is performed when terms are read in so that a ble is read as if it were a boc Note the double use of the character On the one hand it is used as a sentence terminator while on the other it may be used in a string of symbols which make up an atom e g the list functor 2 The rule used to disambiguate terms is that a followed by layout text is regarded as a sentence terminator see Token String page 398 2 2 Declarative Semantics The semantics of definite clauses should be fairly clear from the informal interpretations already given However it is useful to have a precise definition The declarative semantics of
272. edicate is invoked Otherwise error recovery is attempted by user unknown predicate handler 3 as described be low user goal expansion 3 can be regarded as a macro expansion facility It is used for this purpose to support the interface to attributed variables in library atts which defines the predicates M get_atts 2 and M put_atts 2 to access module specific variable attributes These predicates are actually implemented via the user goal_ expansion 3 mechanism This has the effect that calls to the interface predicates are expanded at compile time to efficient code For accessing aspects of the load context e g the name of the file being compiled the predicate prolog load context 2 see Section 7 6 State Info page 104 can be used phrase Phrase List phrase Phrase List Remainder The list List is a phrase of type Phrase according to the current grammar rules where Phrase is either a non terminal or more generally a grammar rule body Remainder is what remains of the list after a phrase has been found If called with 2 arguments the remainder has to be the empty list C 781 Terminal 252 Not normally of direct use to the user this built in predicate is used in the expansion of grammar rules see above It is defined as if by the clause C XIS X S 7 1 3 Input and Output of Terms Most of the following predicates come in two versions with or without a stream argument Pred icates withou
273. edicates must not be defined e g by assert 1 or abolished by abolish 1 2 on the fly e Fastcode compilation is not yet available e The built ins stream select 3 stream interrupt 3 and break 0 are not available e Execution profiling see Section 7 15 Profiling page 121 is not available e The built ins save_program 1 2 restore 1 load_foreign_resource 1 unload foreign_resource 1 and load_foreign_files 2 require that Muse be adjusted to one worker e The statistics 2 options runtime is not meaningful e Prolog cannot be called from C e The hook variable SP_read_hook is not available Muse is still an experimental system and is not formally supported Chapter 4 The Module System 4T 4 The Module System By making use of the module systems facilities programs can be divided into different modules Each module has its own independent predicate name space This is an important feature for the development of larger programs The module system of SICStus Prolog is procedure based This means that only the predicates are local to a module whereas terms are global The module system is flat not hierarchical so all modules are visible to one another It is non strict i e the normal visibility rules can be overridden by special syntax No overhead is incurred on compiled calls to predicates in other modules It is modeled after and compatible with the Quintus Prolog module system Finally using the module system is optiona
274. edicates see 1 and set input 1 SP curout Current output It is initially set equal to SP stdout It can be changed with the predicates tell 1 and set output 1 146 SICStus Prolog Note that these variables are read only They are set but never read by the stream handling 8 5 2 Defining a New Stream The following steps are required to define a new stream in C e Define low level functions character reading writing etc e Initialize and open your stream e Allocate memory needed for your particular stream e Initialize and install a Prolog stream with SP_make_stream e Initialize additional fields Some streams may require additional changes to the fields in the SP_stream structure than the default values set by SP_make_stream 8 5 2 1 Low Level I O Functions For each new stream the appropriate low level I O functions have to be defined Error handling prompt handling and character counting is handled in a layer above these functions They all operate on a user defined private data structure pointed out by user_handle in SP_stream User defined low level I O functions may invoke Prolog code and use the support functions described in the other sections of this chapter int my fgetc void handle Should return the character read or 1 on end of file int my fputc char c int handle Should write the character c and return the character written int my flush void handle Flush the stream Should return 0 on success
275. ee which one is used by this interface 8 2 1 Foreign Resource and Conversion Declarations A foreign resource is a set of C functions defined in one or more files installed as an atomic operation The name of a foreign resource the resource name is an atom which should uniquely identify the resource Thus two foreign resources with the same name cannot be installed at the same time For each foreign resource a foreign resource 2 fact is used to declare the interfaced functions For each of these functions a foreign 2 3 fact is used to specify conversions between predicate arguments and C types These conversion declarations are used for creating the necessary interface between Prolog and C The functions making up the foreign resource the automatically generated interface code and any libraries are compiled and linked to form a linked foreign resource which can be statically or dynamically linked to a Development or Runtime System In all cases the declared predicates are installed by the built in predicate 1oad foreign resource 1 The resource name of a linked foreign resource is derived from its file specification by deleting any leading path and the suffix Chapter 8 Mixing C and Prolog 129 8 2 2 Static and Dynamic linking The interface can be used in two ways With static linking the linked foreign resource is statically linked to a Development or Runtime System load_foreign_resource 1 determines if a resource has been
276. ee eee eee 129 linking static lessen 129 154 lists s tree eM Ace al eens eben ie ieee BOLA 29 lists 5d ii cy RIEF Saag gom ROL 201 loading 1c Re PE 51 73 logic programming iissesee eee ee eee 1 M MACTO EXPANSION A 79 message delegation 0 0 0c esses 332 message Sending 6 cece cece cece eee eens 332 messages SUPPLESSING 6 ee eee 101 meta logical predicate 00 000 co 110 meta predicate declaration 50 56 methodi Lies EU ER MISI E ie PME SRM 327 method dynamic 00 cee eee eee 337 mixing and Prolog 0 0 cece cece ences 127 mode declaration 0 0 0 cece eee eee 56 mode SDE tr ada E weeds Lesa e eae es 5 module declaration 0 000 c eee eee 56 module files tucmrt did MARE MRLs TE A 48 module name expansion 00005 49 56 module system 0000 e cece ie eee eee ee 4T module hidden 00 00 eee eee eee eee 48 module object eer scey een EE RH Ope RENE 345 module source ssseessessse eee 4T module type in cee eee eee eee 47 107 multifile declaration 2 00008 52 54 multiple inheritance sslsesseese esses 334 Muse model i5ie ibtespeRdbRpeR dodo 43 Must tracing em a Ev eG RH PER AAT 45 mutable term uei ras aed ra Ed 113 N nested execution ssesssesssee cece eee eee 16 non unit clause
277. eee ed sere Pee bend tai 287 fdset parts A i sire e Ed saat eas 287 fdset singleton 2 csse 287 fdset size 2 do ete eda XS 287 fdset subset 2 2 0 cece cece teenies 288 fdset subtract 3 esses 288 fdsetoto list 2 1251 uu ad 287 Pdseteto_Tange Diurno 288 fdset union 2 sseeessssse een 288 fdsetJunton 3 ors b tere eher eet ees 288 file exists i1j i LM Wb HE dte td 216 file exists 25 u e IRR URP HEN MUR 216 file property 2 ime eR DG REED IRR ES 216 file search path 2 ea beers va x exa bd 89 fileerrors prolog flag sss 106 file rrors 0 dent ii SR e 92 find this debugger command 67 find constraint 2 esee eee 313 find constraint 3 esee esee 313 findallZ i Loeb tala 119 findalU 4 vs de ute en ra Lea 119 findall_constraints 2 selle esses 313 findall constraints 3 essll sess 313 a geeignete 110 float 1 Coercion ccc ccc ccc cece eens 94 floor 1 function eirese pe ccc cc cece cece 95 Flush output 02s rio ee A a ee 91 flush ou tp t 1 ik via ug E eee d pesa 91 foreygn 2 Sob tees UEM uM HT uide huie 129 LOCO Brin n e ee ra CE Ea 129 168 foreyegn file Q cloro panD c rO E ELER 134 foreign resource 2 ea era rera 129 fOLmdt 2 Je hid iu seni yk E cM I E made 83 format d3 a euh gasps pian P na p RH 83 format to chars 3 0 bbs da PES eed 369 Predicate Index format_to_chars 4
278. ees 142 Concept Index SOck lsuc ce A E AE A pa 229 solutions all di da Sot 117 source information esses eese 19 108 source module oooooooccocccnccrn cr 47 SP term ref C type cococococccoccccccccccino 136 speculative World deer RR Ret e Re 44 SDpY DOIBU disrmiexud eivpixag l n Meis ida evi 62 stand alone application 0e eee ee 151 standard orders zc vp arene XX e des ES 97 State DIOgram sev cx ree EE uerus 104 State saved cie aran da ea c b penes ig ans 17 static linking lt iii 129 154 st tie Object io ss dicara peeo ce ee RR een 327 336 store consistent cles 283 Store CONSUELA ia E pa etd 283 store contradictory sess eese eee 283 SM er ec Rr a S VA OUR EA I RI 71 stream eid Ofo iiie veria cas whet Ee beris 91 SUI A ise br A tel nied ht 30 subsumption n nueiritenpeuh cue gabe e 205 suppressing messages csse 101 Suspension y i piep barrei ph bf e ben EEE phar ndeki 44 suspension voluntary 00 0c cece ener eee eee 44 Synchronlzatlon ari 231 Sy chronized 2e eer orbe i eqe runs 44 SOI cea roe ee Era RC e ORI 14 system development 0 0 cece cece eee eens 6 system Operating essa i E a EAE AE RRENA 215 system runtime rapen iaig rr 6 T tail PeCurslON sos duse REDDE E EN SS 178 COL dara ale abe wlth AA AAA 27 term COMPALISON 1 eee eee 97 term CONVETSIONS 6 6 eee cece eee ee eee eee 135 term 1 0
279. el Programs A Guide to the Per plexed ACM Computing Surveys September 1989 Clocksin amp Mellish 81 W F Clocksin and C S Mellish Programming in Prolog Springer Verlag 1981 Colmerauer 75 A Colmerauer Les Grammaires de Metamorphos Technical Report Groupe d Intelligence Artificielle Marseille Luminy November 1975 Colmerauer 90 Colmerauer A An Introduction to Prolog III Communications of the ACM 33 7 69 90 1990 406 SICStus Prolog Conery 83 J Conery The AND OR Process Model for Parallel Interpretation of Logic Programs PhD thesis University of California at Irvine 1983 Diaz amp Codognet 93 D Diaz and P Codognet A Minimal Extension of the WAM for clp FD Proceedings of the International Conference on Logic Programming MIT Press 1993 Elshiewy 90 N A Elshiewy Robust Coordinated Reactive Computing in Sandra SICS Dissertation Series 03 1990 Falkman amp Torgersson 94 G Falkman and O Torgersson Programming Methodologies in GCLA in Proceed ings of the fourth Workshop on Extensions of Logic Programming ELP LNAI 798 Springer Verlag 1994 Gorlick amp Kesselman 87 M M Gorlick and C F Kesselman Timing Prolog Programs Without Clocks Proc Symposium on Logic Programming pp 426 432 IEEE Computer Society 1987 Hausman 90 B Hausman Pruning and Speculative Work in OR Parallel PROLOG PhD thesis Department of Telecommunication and Computer Systems The Royal Inst
280. elow If an exception term exists SP_exception_term retracts it and stores it as the value of an SP term ref which must exist prior to the call and returns nonzero Otherwise it returns zero int SP exception term SP term ref t To raise an exception from a C function called from Prolog just call SP raise exception t where t is the SP term ref whose value is the exception term The glue code will detect that an exception has been raised any value returned from the function will be ignored and the exception will be passed back to Prolog void SP raise exception SP term ref t 8 5 SICStus Streams With the SICStus Prolog C interface the user can define his her own streams as well as from C read or write on the predefined streams The stream interface is modeled after Quintus Prolog release 2 It provides e C functions to perform I O on Prolog streams This way you can use the same stream from Prolog and C code e User defined streams You can define your own Prolog streams in C e Bidirectional streams A SICStus stream supports reading or writing or both e Hookable standard input output error streams Chapter 8 Mixing C and Prolog 145 8 5 1 Prolog Streams From the Prolog level there is a unique number that identifies a stream This identifier can be converted from to a Prolog stream stream_code Stream StreamCode stream code Stream StreamCode StreamCode is the C stream identifier an integer corres
281. else and not provable The built in predicates which are concerned with grammar rules and other compile consult time transformations are as follows expand_term Term1 Term2 If Terml is a term that can be transformed Term2 is the result Otherwise Term2 is just Term1 unchanged This transformation takes place automatically when gram mar rules are read in but sometimes it is useful to be able to perform it explicitly Grammar rule expansion is not the only transformation available the user may define clauses for the predicate user term expansion 2 4 to perform other transforma tions user term expansion Terml Layoutl Term2 Layout2 is called first and only if it fails is the standard expansion used term expansion Terml TermOr Terms user term_expansion Terml TermOrTerms term_expansion Term1 Layout1 TermOrTerms Layout2 user term_expansion Term1 Layout1 TermOrTerms Layout2 A hook predicate which defines transformations on terms read while a program is consulted or compiled It is called for every Term read including at end of file represented as the term end_of_file If it succeeds TermOrTerms is used for further processing otherwise the default grammar rule expansion is attempted It is often useful to let a term expand to a list of commands and clauses which will then be processed sequentially The 4 arguments version also defines transformations on the layout of the term read so that the sour
282. ement of universally quantified variables can save considerable time and space findall Template Goal Bag Remainder Same as findall 3 except Bag is the list of solution instances appended with Re mainder which is typically unbound 7 13 Coroutining The coroutining facility can be accessed by a number of built in predicates This makes it possible to use coroutines in a dynamic way without having to rely on block declarations when Condition Goal Blocks Goal until the Condition is true where Condition is a Prolog goal with the restricted syntax nonvar X ground X X Y Condition Condition Condition Condition For example when nonvar X X Y ground T process X Y T freeze X Goal Blocks Goal until nonvar X see Section 7 7 Meta Logic page 110 holds This is defined as if by freeze X Goal when nonvar X Goal or 120 SICStus Prolog block freeze 7 freeze _ Goal Goal frozen Var Goal If some goal is blocked on the variable Var or Var has attributes that can be interpreted as a goal see Chapter 14 Attributes page 193 then that goal is unified with Goal If no goals are blocked Goal is unified with the atom true If more than one goal is blocked a conjunction is unified with Goal dif X 7Y Constrains X and Y to represent different terms i e to be non unifiable Calls to dif 2 either succeed fail or are blocked depending on whether X an
283. en that atom is assigned to name and 0 is assigned to arity This is similar to calling functor 3 with the first argument bound to a compound term or an atom and the second and third arguments unbound int SP get list SP term ref t SP term ref head SP term ref tail Assigns to head and tail the head and tail of a Prolog list int SP get arg int i SP term ref t SP term ref arg Assigns to arg the i th argument of a Prolog compound term This is similar to calling arg 3 with the third argument unbound 8 3 4 Testing Prolog Terms There is one general function for type testing of Prolog terms and a set of specialized more efficient functions one for each term type int SP term type SP term ref t Depending on the type of the term t one of SP TYPE VARIABLE SP TYPE INTEGER SP TYPE FLOAT SP TYPE ATOM or SP TYPE COMPOUND is returned int SP is variable SP term ref t Returns nonzero if the term is a Prolog variable zero otherwise int SP is integer SP term ref t Returns nonzero if the term is a Prolog integer zero otherwise 140 SICStus Prolog int SP is float SP term ref t Returns nonzero if the term is a Prolog float zero otherwise int SP is atom SP term ref t Returns nonzero if the term is a Prolog atom zero otherwise int SP is compound SP term ref t Returns nonzero if the term is a Prolog compound term zero otherwise int SP is list SP term ref t Returns nonzero if the term is a Prolog
284. eneral 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 equa tions 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 Referencing this Software 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 Artificial Intelligence Vienna TR 95 09 1995 Acknowledgments The development of this software was supported by the Austrian Fonds zur Foerderung der Wis senschaftlichen Forschung under grant P9426 PHY Financial support for the Austrian Research Institute for Artificial Intelligence is provided by the Austrian Federal Ministry for Science and Research We include a collection of examples that has been distributed with the Monash University version of clp R Heintze et al 87 and its inclus
285. eparation into files is unnatural or inconvenient one can easily ensure that the compile time environment is up to date by doing ensure_loaded Files fcompile Files Since module name expansion takes place at compile time the module into which the file is to be loaded must be known when compiling to object files This is no problem for module files because the module name is picked from the module declaration When non module files are compiled the file name may be prefixed with the module name that is to be used for expansion fcompile Module Files If an object file is loaded into a different module from which it was compiled for a warning is issued Chapter 6 Debugging 59 6 Debugging This chapter describes the debugging facilities that are available in Development Systems The purpose of these facilities is to provide information concerning the control flow of your program In the Muse Development System the debugger effectively sequentializes the execution Other tools see Section 3 4 Visualization Tools page 44 must be used to debug the parallel aspects of execution The main features of the debugging package are as follows e The Procedure Box model of Prolog execution which provides a simple way of visualizing control flow especially during backtracking Control flow is viewed at the predicate level rather than at the level of individual clauses e The ability to exhaustively trace your program or
286. er 4 Module Intro page 47 5 2 8 Mode Declarations A declaration mode ModeSpec ModeSpec where each ModeSpec is a mode spec has no effect whatsoever but is accepted for compatibility reasons In some Prologs this declaration helps reduce the size of the compiled code for a predicate and may speed up its execution Unfortunately writing mode declarations can be error prone and since errors in mode declaration do not show up while running the predicates interpretively new Chapter 5 Loading Programs 57 bugs may show up when predicates are compiled However mode declarations may be used as a commenting device as they express the programmer s intention of data flow in predicates 5 2 9 Parallel and Sequential Declarations The following declarations serve for the explicit control of parallelism in the Muse Development System parallel PredSpec PredSpec enables the clauses of the specified predicates to be run in parallel this is the default sequential PredSpec PredSpec prohibits the clauses of the specified predicates from running in parallel Universal versions of both declarations also exist sequential parallel This indicates to the compiler that all subsequent predicates in the given file become sequential or parallel unless specifically declared otherwise The default is to treat all predicates as parallel Se quential declarations may be necessary to prevent infinite loops i
287. eres 88 ttyge tO diiisounn Di saute ig RR ERI e ice d 88 ttynkl O ive xb APA NEM ie E b INA 88 ttyput l4znctikrstbchn birth br Pied beats 88 EtySklp lilnonsSs unserer bl one Mb ane Did erben ud 88 ttytab l cc enne b uM DARREN VULG QE Md 88 type error 4 error class o ooo oooomomo oo 103 typein module prolog flag o ooooooo o 107 U ugraph to wgraph 2 sss nn 225 nconstraiued T i orsi aii iria 314 unify debugger command 0005 68 unify with occurs check 2 esses sess 206 unknown prolog flag 0c cece eee eee 106 nEnoWh 2 t bb VT EY e ed Es 15 120 unknown predicate handler 3 103 unload foreign resource 1 sss sess 133 update mutable 2 sisse 113 usemmod le 1 eripi eS Ie PR CIS ePUMpDe YI 75 USS MOGUL S Zitarrosa 75 usemnodule 3 4 bun uote Ue uid uti 75 user error exception 1 isses 69 user file search path 2 sse 89 user goal expansion 3 sss sese T9 user library directory 1 sss sss 90 user method expansion 3 s sssssssn 329 ser portray is deleviei r9 ER b ORE b 82 user portray message 2 sss 102 user term expansion 2 see T9 user term expansion A lle T9 user unknown predicate handler 3 103 user user help 0 s ie ole xi url px es cat 126 user error prolog flag sss 107 user_error stream alias
288. ernatives outstanding Execution proceeds to C If a cut that removes the outstanding alternatives is encountered Cleanup is executed with continuation to proceed after the cut Also if an exception E that will be caught by an ancestor of the call cleanup 2 Goal is raised Cleanup is executed with continuation raise exception E 3 Goal fails Cleanup is executed with continuation fail Goal raises an exception E Cleanup is executed with continuation raise exception E In a typical use of call cleanup 2 Cleanup succeeds deterministically after perform ing some side effect otherwise unexpected behavior may result Note that the Prolog top level operates as a read execute fail loop which backtracks into or cuts the query when the user types or RET respectively Also the predicates halt 0 abort 0 and reinitialise O are implemented in terms of exceptions All of these circumstances can trigger the execution of Cleanup 7 5 Error and Exception Handling The two built in predicates on exception 3 and raise exception 1 are used to alter the control flow to meet exception and error conditions The equivalent of a raise exception 1 is also executed by the built in predicates when errors occur on exception Pa ttern ProtectedGoal Handler ISO raise exception Exception ISO on exception 3 calls ProtectedGoal If this succeeds or fails so does the call to on exception 3 If however during the execution of ProtectedGoal
289. es or source code p1 files They must be explicitly loaded by the program at runtime your linked foreign resources Any linked foreign resources which are not statically linked to the executable including any linked foreign resources for library modules which are located in SP_PATH library Also on most UNIX platforms it is necessary to set an environment variable typically LD_LIBRARY_ PATH for shared objects to be found at runtime See Section 1 1 1 Finding Libraries at Runtime page 9 156 SICStus Prolog 8 9 Development Systems This describes how to create a Development System with a set of linked foreign resources For the SICStus library modules containing C code such linked foreign resources already exist in SP_PATH library For user foreign code you must first create linked foreign resources for them A utility command is provided for the generation of such systems This command located in SP_PATH bin is configurable as described in the Release Notes spmkds help S Executable Resources Generates a Development System with any foreign resources mentioned in Resources statically linked The resources must be created with the static option Note however that a statically linked dynamic resource is not in general statically linked from the operating system s point of view It must therefore be accessible at runtime as well as at build time The option S causes the SICStus Runtime
290. es For example to create an instance of the class history_point the following code is used new Instance xy IX IY super lt new Instance xy IX IY Instance set history IX IY amp Note that the delegation of new 2 to super is necessary in order to create an object whose super is history point and not point The example shows how delegation can be effective as a tool for flexible sharing of concepts in multiple inheritance Four prototypes are defined point history point bounded point and bh point The latter is a bounded history point An instance of the point class is a point that moves in 2 D space and that can be displayed An instance of the history point class is similar to an instance of the point class but also keeps a history of all the moves made so far An instance of bounded point is similar to an instance of point but moves only in a region of the 2 D space Finally an instance of bh point inherits most of the features of a bounded point and a history point The default inheritance does not work for the methods display 1 and move 2 in bh point In heritance by delegating messages to both supers of bh point results in redundant actions moving and displaying the point twice Selective delegation solves the problem Taken from Elshiewy 90 point super object amp attributes x 0 y 001 amp xy X Y get x X get y WM new Instance xy IX IY Super instance In
291. es beginning with or are treated specially For example sample pl is equivalent to home sics al sample p1l if home sics al is the user s home directory This is also equivalent to HOME sample p1 as explained below Chapter 7 Built In Predicates 73 e clyde sample pl is equivalent to home sics clyde sample pl if home sics clyde is Clyde s home directory SUTIL sample pl is equivalent to usr local src utilities sample pl provided the value of the environment variable UTIL is usr local src utilities Failure to open a file normally causes an exception to be raised This behavior can be turned off and on by of the built in predicates nofileerrors 0 and fileerrors 0 described below 7 1 1 Reading in Programs When the predicates discussed in this section are invoked filenames are relative to the current working directory During the load the current working directory is temporarily changed to the directory containing the file being read in This has the effect that if one of these predicates is invoked recursively the filename of the recursive load is relative to the directory of the enclosing load See Chapter 5 Load Intro page 51 for an introduction to these predicates Directives will be executed in order of occurrence Be aware of the changed current working directory as it could have an effect on the semantics of directives Only the first solutio
292. esee 82 Write term 2 We MEM tede uS 83 Write term Iuei Seas eee apelin PES CERNI ERR 83 write_to_chars 2 sess 369 Write to chars 3 imita tard po 369 Wrlteg i ele b b AS 82 WLCD seeks pt a eios 82 X Xre f lg A qup 377 Z zip debugger command e cece eens 65 420 SICStus Prolog Prolog Objects Method Index Prolog Objects Method Index A abolish 0 object method 05 343 ancestor 1 utility method 344 ancestor 2 utility method 344 ancestors 1 utility method 344 ancestors 2 utility method 344 and_cast 2 utility method 344 assert 1 object method 339 343 assert 2 object method 005 343 asserta 1 object method 339 343 asserta 2 object method 005 343 assertz 1 object method 339 343 assertz 2 object method 05 343 attributes 1 universal method 341 augment 1 object method 05 343 augmenta 1 object method 000 343 augmentz 1 object method oo o ooooooo 343 D descendant 1 utility method 344 descendant 2 utility method 344 descendants 1 utility method 344 descendants 2 utility method 344 dynamic 0 object method
293. ested in the first solution is to call the function SP_query It will create a goal from the predicate definition and the arguments and try to prove it The call will return SP_SUCCESS if the goal succeeded SP_FAILURE if it failed and SP_ERROR if an error condition occurred int SP_query SP_pred_ref predicate SP_term_ref argi If you are only interested in the side effects of a predicate you can call SP_query_cut_fail It will try to prove the predicate cut away the rest of the solutions and finally fail This will reclaim the storage used after the call int SP_query_cut_fail SP_pred_ref predicate SP term ref argl 8 4 2 Finding Multiple Solutions of a Call If you are interested in more than one solution a more complicated scheme is used You find the predicate definition as above but you don t call the predicate directly 1 Set up a call with SP open query 142 SICStus Prolog 2 Call SP_next_solution to find a solution Call this predicate again to find more solutions if there are any 3 Terminate the call with SP_close_query or SP cut query O The function SP open query O will return an identifier of type SP qid that you use in successive calls or NULL if given an invalid predicate reference Note that if a new query is opened while another is already open the new query must be terminated before performing any action on the old one That is queries must be strictly nested SP qid SP open q
294. et singleton Set Elt Set is an FD set containing Elt only At least one of the arguments must be ground fdset_min Set Min Min is the lower bound of Set fdset_max Set Min Max is the upper bound of Set This operation is linear in the number of intervals of Set fdset_size Set Size Size is the cardinality of Set represented as sup if Set is infinite This operation is linear in the number of intervals of Set list to fdset List Set Set is the FD set containing the elements of List Slightly more efficient if List is ordered fdset to list 45et List List is an ordered list of the elements of Set which must be finite range_to_fdset Range Set Set is the FD set containing the elements of the ConstantRange see Syntax of In dexicals page 301 Range 288 SICStus Prolog fdset_to_range Set Range Range is a constant interval a singleton constant set or a union of such denoting the same set as Set fdset_add_element Set1 Elt Set2 Set2 is Set1 with Elt inserted in it fdset_del_element Set1 Elt Set2 Set2 is like Set1 but with Elt removed fdset_disjoint Set1 Set2 The two FD sets have no elements in common fdset_intersect Set1l Set2 The two FD sets have at least one element in common fdset_intersection Set1 Set2 Intersection Intersection is the intersection between Set1 and Set2 fdset_intersection Sets Intersection Intersection is the intersectio
295. eta logical and perform operations that require reasoning about the current instantiation of terms or decomposing terms into their constituents Such operations cannot be expressed using predicate definitions with a finite number of clauses var X ISO Tests whether X is currently uninstantiated var is short for variable An uninstan tiated variable is one which has not been bound to anything except possibly another uninstantiated variable Note that a structure with some components which are unin stantiated is not itself considered to be uninstantiated Thus the directive var foo X Y always fails despite the fact that X and Y are uninstantiated nonvar X ISO Tests whether X is currently instantiated This is the opposite of var 1 ground X Tests whether X is completely instantiated i e free of unbound variables In this context mutable terms are treated as nonground so as to make ground 1 a monotone predicate atom X ISO Checks that X is currently instantiated to an atom i e a non variable term of arity 0 other than a number float X ISO Checks that X is currently instantiated to a float integer X ISO Checks that X is currently instantiated to an integer number X ISO Checks that X is currently instantiated to a number atomic X ISO Checks that X is currently instantiated to an atom or number simple X Checks that X is currently uninstantiated or instantiated to an atom or n
296. etry X leq Y Y leq X So the two con straints are replaced by B C Since B C makes B and C equivalent CHR 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 leq 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 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 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 4 generate candidates absorb J 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
297. ext paragraph i e empty line M h Mark paragraph Chapter 1 How to Run Prolog 21 M C n M C p Go to matching right parenthesis Go to matching left parenthesis Creates a comment at comment column This comment will always stay at this position when the line is indented regardless of changes in the text earlier on the line provided that prolog align comments flag is set to t C c C t C u C c C t Enable and disable tracing respectively C c C d C u C c C d Enable and disable debugging respectively C c C z C u C c C z C c C s C c C n C c C v a Enable and disable zipping respectively Insert the PredSpec of the current predicate into the code Insert the name of the current predicate into the code This can be useful when writing recursive predicates or predicates with several clauses See also the prolog electric dot flag variable below Convert all variables in a region to anonymous variables This can also be done us ing the Prolog Transform All variables to menu entry See also the prolog electric underscore flag Emacs variable Help on predicate requires the SICStus info files to be installed and the Emacs variable prolog info predicate index to be set to the predicate index of the info files defaults to sicstus Predicate Index 1 11 4 Mode Line If working with an application split into several modules it is recommended to let the source files begin with a mode line VA
298. f command specifications and corresponding translations Chapter 34 Tcl Tk Interface 363 set x 32 gt get x 32 set x br a b c gt set x fa b c panel value_info name configure min text br write display 1 gt panel value_info name configure text display 1 34 2 Tcl to Prolog There are two new Tcl commands defined in this library prolog Goal Goal is a string containing the printed representation of a Prolog goal The goal will be called in the user module unless it is prefixed with another module name The call is always deterministic The result of the call is returned as wn if execution succeeds The value of any of the variables in the goal that is bound to a term will be returned to Tcl in the array prolog variables with the variable name as index The term is converted to Tcl using the same conversion as used for Tcl commands see Section 34 1 1 Command Format page 362 o if the execution fails Tcl exception if a Prolog exception is raised The error message will be Prolog Exception appended with a string representation of the Prolog excep tion An example test_callback Result tcl new Interp tcl eval Interp if prolog foo X Y 2 1 NN lappend res prolog variables X NN prolog_variables Y NN prolog_variables Z Result tcl_delete Interp foo 1 bar a b c The query test callback Result will succeed binding Result
299. f world Print radix The argument is an integer Identical to Nr except that the letters A Z will denote digits larger than 9 Example format Hello 16R world 15 Hello F world Print string The argument is a list of character codes Exactly N char acters will be printed N defaults to the length of the string Example format Hello 4s 4s new world Hello new worl format Hello s world new Hello new world Ignore The argument which may be of any type is ignored Example format Hello i s world old new Hello new world 86 ud o Nn N SICStus Prolog Print canonical The argument may be of any type The argument will be passed to write_canonical 1 see Section 7 1 3 Term I O page 80 Example format Hello k world a b c Hello a b c world Print The argument may be of any type The argument will be passed to print 1 see Section 7 1 3 Term I O page 80 Example assert portray X Y print cons X Y format Hello p world a b c Hello cons a cons b cons c 1 world Print quoted The argument may be of any type The argument will be passed to writeq 1 see Section 7 1 3 Term I O page 80 Example format Hello q world A B Hello A B world Write The argument may be of any type The argu
300. fault unless SIC Stus Prolog has been installed with support for fastcode compilation fastcode Compilation produces native machine instructions Currently only available for 68K Sparc and MIPS platforms but not for Muse Fastcode runs about 3 times faster than compactcode This is the default if SICStus Prolog has been installed with support for fastcode compilation profiledcode Compilation produces byte coded abstract instructions instrumented to produce exe cution profiling data See Section 7 15 Profiling page 121 Profiling is not available in Runtime Systems debugcode Compilation produces interpreted code i e compiling is replaced by consulting The compilation mode can be changed by issuing the directive prolog_flag compiling OldValue NewValue A Prolog program consists of a sequence of sentences see Sentence page 396 Commands and queries encountered among the sentences are executed immediately as they are encountered unless they can be interpreted as declarations see Section 5 2 Declarations page 53 which affect the treatment of forthcoming clauses Clauses are loaded as they are encountered A Prolog program may also contain a list of sentences including the empty list This is treated as equivalent to those sentences occurring in place of the list This feature makes it possible to have user term expansion 2 4 see Section 7 1 2 Definite page 76 return a list of sentences instead of a s
301. fied with or without a trailing ql or a list of filenames For each filename in the list this predicate will search for a file with the suffix ql added if not specified This directive has the same effect as if the source files had been compiled using compile 1 directly but see Section 5 3 Considerations page 58 Finally to ensure that some files have been compiled or loaded use the built in predicate ensure loaded Files where Files is either a single filename or a list of filenames similar to the arguments accepted by the above predicates The predicate takes the following action for each File in the list of filenames 1 If the File is user compile user is performed 2 If File cannot be found not even with a p1 or q1 extension an error is signaled 3 If an object file is found which has not yet been loaded or which has a modification time more recent than what was recorded for the file when it was previously loaded the file is loaded 4 If a source file is found which has not yet been loaded or which has a modification time more recent than what was recorded for the file when it was previously loaded the file is compiled 5 If both a source file and an object file are found item 3 or 4 applies depending on which file was modified most recently in case 4 ensure 1loaded 1 does not cause object files to become recompiled 6 Otherwise no action is taken 5 2 Declarations When a program is to
302. fined in the IEEE standard Variables in an arithmetic expression which is to be evaluated may be bound to other arithmetic expressions rather than just numbers e g evaluate Expression Answer Answer is Expression evaluate 24 9 Ans Ans 216 yes Arithmetic expressions as described above are just data structures If you want one evaluated you must pass it as an argument to one of the built in predicates listed below Note that it only evaluates one of its arguments whereas all the comparison predicates evaluate both of theirs In the following X and Y stand for arithmetic expressions and Z for some term Z is X ISO X which must be an arithmetic expression is evaluated and the result is unified with Z X Y ISO The numeric values of X and Y are equal X Y ISO The numeric values of X and Y are not equal X Y ISO The numeric value of X is less than the numeric value of Y X Y ISO The numeric value of X is greater than the numeric value of Y X lt Y ISO The numeric value of X is less than or equal to the numeric value of Y Chapter 7 Built In Predicates 97 X gt Y ISO The numeric value of X is greater than or equal to the numeric value of Y 7 3 Comparison of Terms These built in predicates are meta logical They treat uninstantiated variables as objects with values which may be compared and they never instantiate those variables They should not be used when what yo
303. fining hook predicates A hook predicate is a user defined predicate that somehow alters or customizes the behavior of SICStus Prolog number of such hook predicates are described in this manual Often an application needs to combine the functionality of several software modules some of which define clauses for such hook predicates By simply declaring every hook predicates as multifile the functionality of the clauses for the hook predicates is automatically combined If this is not done the last software module to define clauses for a particular hook predicate will effectively supersede any clauses defined for the same hook predicate in a previous module If a file containing clauses for a multifile predicate is reloaded the old clauses from the same file are removed The new clauses are added at the end If a multifile predicate is loaded from a file with no multifile declaration for it the predicate is redefined as if it were an ordinary predicate i e the user is asked for confirmation Clauses of multifile predicates are currently always loaded in interpreted form even if they were processed by the compiler If performance is an issue define the multifile predicates as unit clauses or as clauses with a single goal that just calls an auxiliary compiled predicate to perform any time critical computation If a multifile predicate is declared dynamic in one file it must also be done so in the other files from where it is loaded Hook
304. 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 will be removed The rule says that if we find X leq Y and another X leq Y in the constraint store we can remove one Chapter 31 Constraint Handling Rules 307 Finally the rule transitivity states that the conjunction X leq Y Y leq Z implies X leq Z Op erationally 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 leq C illustrates The first two con straints cause CHR transitivity to fire and add C leq B to the query This new constraint together with B leq C matches the head of CHR antisymm
305. fter task 2 started domain S1 S2 S3 0 20 serialized precedence 1 82 83 5 5 5 d 2 1 sup d 2 3 10 S1 in 0 15 S2 in 5 20 S3 in 0 20 The bounds of S1 and 2 changed because of the precedence constraint Setting 2 to 5 will propagate 120 and 83 in 15 20 The following constraint can be thought of as constraining n tasks each with a start time Sj a duration Dj and a resource amount Rj so that the total resource consumption does not exceed Limit at any time cumulative Starts Durations Resources Limit where Starts S1 Sn Durations D1 Dn Resource R1 Rn are lists of domain variables with finite bounds or integers and Limit is a domain variable with finite bounds or an integer Let a min S1 59n b max S1 D1 Sn Dn Rij Rj if Sj lt i Sj Dj Rij 0 otherwise The constraint holds if Ril Rin lt Limit for all a lt i lt b The cumulative 4 constraint is due to Aggoun and Beldiceanu Aggoun amp Beldiceanu 92 The current implementation is incomplete and takes O n 2 space 280 SICStus Prolog 30 3 5 User Defined Constraints New primitive constraints can be added defined by the user on two different levels On a higher level constraints can be defined using the global constraint programming interface see Section 30 8 Defining Global Constraints page 285 Such constraints can embody specialized algorithms and use the full power of Pr
306. fy_attributes Var Value Goals A hook predicate This predicate is called whenever a variable Var that might have attributes in Module is about to be bound to Value it might have none The unifi cation resumes after the call to verify_attributes 3 Value is a non variable term or another attributed variable Var might have no attributes present in Module the unification extension mechanism is not sophisticated enough to filter out exactly the variables that are relevant for Module verify_attributes 3 is called before Var has actually been bound to Value If it fails the unification is deemed to have failed It may succeed non deterministically in which case the unification might backtrack to give another answer It is expected to return in Goals a list of goals to be called after Var has been bound to Value verify_attributes 3 may invoke arbitrary Prolog goals but Var should not be bound by it Binding Var will result in undefined behavior If Value is a non variable term verify_attributes 3 will typically inspect the at tributes of Var and check that they are compatible with Value and fail otherwise If Value is another attributed variable verify_attributes 3 will typically copy the at tributes of Var over to Value or merge them with Value s in preparation for Var to be bound to Value In either case verify_attributes 3 may determine Var s current attributes by calling get_atts Var List with an unbound List An impor
307. g constraints together with minimum 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 pathc pl the most simple example of a handler for path consistency two rules Chapter 31 Constraint Handling Rules 325 primes pl elegant implementations of the sieve of Eratosthenes reminiscent of the chemical ab stract 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 constraints 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 problems 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 cons
308. g 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 Example 8 1 apply era absorb 8 prime 4 lt c14 gt X prime 8 H lt c6 gt absorb 8 Q prime 4 lt c14 gt prime 8 lt c6 gt lt gt 8 mod 4 true 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 command without arguments resets the limit to 10 With an argument of n the limit is set to n treating 0 as infinity abort calls the built in predicate abort 0 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 Chapter 31 Constraint Handling Rules 323 h help displays the table of options given above 31 5 Programming Hints This section gives you some programming hints for CHR For maximum efficiency of your constraint handler se
309. g the same finite function from Keys to Values ord list to assoc List Assoc List is a proper list of Key Value pairs keysorted and Assoc is an association tree specifying the same finite function from Keys to Values map assoc Pred Assoc Assoc is an association tree and for each Key if Key is associated with Value in Assoc Pred Value is true map assoc Pred OldAssoc NewAssoc OldAssoc and NewAssoc are association trees of the same shape and for each Key if Key is associated with Old in OldAssoc and with New in NewAssoc Pred Old New is true put assoc Key OldAssoc Val NewAssoc OldAssoc and NewAssoc define the same finite function except that NewAssoc asso ciates Val with Key OldAssoc need not have associated any value at all with Key del assoc Key OldAssoc Val NewAssoc OldAssoc and NewAssoc define the same finite function except that OldAssoc asso ciates Key with Val and NewAssoc doesn t associate Key with any value del min assoc OldAssoc Key Val NewAssoc OldAssoc and NewAssoc define the same finite function except that OldAssoc asso ciates Key with Val and NewAssoc doesn t associate Key with any value and Key precedes all other keys in OldAssoc del max assoc OldAssoc Key Val NewAssoc OldAssoc and NewAssoc define the same finite function except that OldAssoc asso ciates Key with Val and NewAssoc doesn t associate Key with any value and Key is preceded by all othe
310. gin prolog flag sss 105 all different l vis Pb SG MARE E is 278 all di tilda a erae 278 ancestors debugger command oo o ooooo o 67 append 3 cui be a E EUR Rae eR 201 ALETAS 22g sss vevtrev ere v verre urcM OE eru up 189 areta 3 ene Riera ip hae bares Cetera a A 189 A goa 189 BEBE a cesse a ed ae e Ent 111 SICStus Prolog array to list 2 i ee ha i ete ret ias 189 aset 4 ii a a ea ee 190 asin 1 function ccc cece eens 95 asinh 1 function 00 ccc cc cece eens 95 assert ilucon emeneree ca BEAMS 114 assett 2 4 cota o m Ua tn C m Ms tt 114 asserta d c a ERN S I 114 asserta 2 u c e iet rete ute pte ih 114 assettz 1 5o RE t ML ERU At 114 assertz 2 5 jv c M a MO MC es 114 asSignment 2 sii ve be rd ES RpDUURER 278 asSoc to list 2 u i yore ne ee A E SA 191 at end of line 0 sss 92 at end of _line 1 0 cece ccc ees 92 at end of _stream 0 0 0 cece cece eee ee 91 at_end_of_stream 1 0 cece cece eee ee 91 at n 1 f nctlon si sauike aeons REIR SEA 95 at n2 2 function i llli vp DA EPIS 95 atanh 1 function 0c ccc cece eee nae 96 AtOM o eco TED Gone ta DeY pr aga ees 110 aton clhars 2 i ere rs ted 112 atom garbage collection statistics 2 option P dete tsm A a tae came ogee circo A 109 atom to chars 2 ii2 doi ese ie PERRA 369 atom to chars 3 ibus db EPIS 369 atomic d u hah gifs ku DidifxPeTGX a WORD Rees 110 atoms st
311. gly related to last call optimization see below Indexing applies to interpreted clauses as well as to compiled clauses 10 3 Last Call Optimization The compiler incorporates last call optimization to improve the speed and space efficiency of de terminate predicates When execution reaches the last goal in a clause belonging to some predicate and provided there are no remaining backtrack points in the execution so far of that predicate all of the predicate s local working storage is reclaimed before the final call and any structures it has created become eligible for garbage collection This means that programs can now recurse to arbitrary depths without necessarily exceeding core limits For example cycle State transform State Statei cycle Statel where transform 2 is a determinate predicate can continue executing indefinitely provided each individual structure State is not too large The predicate cycle is equivalent to an iterative loop in a conventional language To take advantage of last call optimization one must ensure that the Prolog system can recognize that the predicate is determinate at the point where the recursive call takes place That is the system must be able to detect that there are no other solutions to the current goal to be found by subsequent backtracking In general this involves reliance on the Prolog compiler s indexing and or use of cut see Section 2 5 Cut page 36 10 4 If Then Else Compi
312. h 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 Examples 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 clpr sin cos X 0 5 lt 0 0 254 SICStus Prolog 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 Y 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 clpq Z 1542 14 1542 13 1054Z 12 455 42 11 136542 10 3003 polynomial continues for a few pages O Computing its roots is another story 29 3 1 How Nonlinear Residues are made to disappear Binding variables that appear in nonlinear residues will reduce the complexity of the nonlinear expressions and eventually results in linear expressions clp q fexp X Y 1 2 3 X X4Y Y cl pq Y 2 X72 2 Y X 2 K 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
313. h e de en i p fa Rika 367 GOLA zi menester rte Maen ee eter el Deest 359 generalized Horn clause language 359 generic object sees cis ot co eie eed edits 331 generic object implementation 348 global constraint sese 285 goal fovea heed ee ees a he a ERO 30 goal ancestor iccell k Lh ta be A vee Eh eee ij eu 64 goal blocked ia EN ete ete 64 grammar rule eek rr RES cee onde bk eae 76 graphical tracing i e 44 graphs unweighted oooooooocccccccccccncr o 221 graphs weighted isses 225 green CUb iss oro VE ERU HERR e Ten T RR 37 guarded clause ee bee 179 Concept Index H handling interrupt 2 0 200008 142 handling Signals 02 enel Reds 142 ead ite EET 30 peapa sn e oro t e e pelle ae eee eee 199 hidden module 00 0 cece eee eee ee 48 hierarchy object oriri it arn cece ee eee eee eee 333 hook functions for 1 O 0 00 cee e eee 150 hook functions for reinitialization 150 hook predicate ooooccooccccoccccccn cr 54 Horn clause ii A 27 I I O hook functions isses 150 if then else ceed Ye cea eae oe Raa ee 178 implicit parallelism 000020 00 ee Al IMPOR ION ciis cies Dada e a ed alee Bae 49 imported predicate 0 cece eee eee ee 4T indexed term ooocoocccoccccocc rro 236 indesical i cR RE RUE emu Sites 291 o si loiter c thai be kek Sh eee b 1
314. hapter 30 Constraint Logic Programming over Finite Domains 297 e Otherwise if D X S is disjoint from S R and R is ground in S all possible values for X will make C false and so C is detected as disentailed e Otherwise D X S contains some values that could make C true and some that could make C false and the indexical suspends A checking indexical is scheduled for execution as follows e it is evaluated initially as soon as it has become anti monotone e it is re evaluated when one of the following conditions occurs the domain of X has been pruned or X has been assigned the domain of a variable Y that occurs as dom Y or card Y in R has been pruned the lower bound of a variable Y that occurs as min Y in R has been increased Rw N e the upper bound of a variable Y that occurs as max Y in R has been decreased 30 9 8 Goal Expanded Constraints The arithmetic membership and propositional constraints described earlier are transformed at compile time to conjunctions of goals of library constraints Sometimes it is necessary to postpone the expansion of a constraint until runtime e g if the arguments are not instantiated enough This can be achieved by wrapping call 1 around the constraint Although space economic linear in the size of the source code the expansion of a constraint to library goals can have an overhead compared to expressing the constraint in terms of indexicals Temporary variables holding intermedia
315. haracter escaping can be turned off for compatibility with old code The following escape sequences exist b backspace character code 8 Xt horizontal tab character code 9 n newline character code 10 v vertical tab character code 11 f form feed character code 12 Vr carriage return character code 13 Ve escape character code 27 Md Vo delete character code 127 Na alarm character code 7 Nx CD the character code CD two hexadecimal digits octal the character code octal base 8 where octal is up to 3 octal digits 402 SICStus Prolog Y char the character code char mod 32 where char is a letter layout char A single layout character for example a newline is ignored c All characters up to but not including the next non layout character are ignored ot her A character not mentioned in this table stands for itself For example inserts a single backslash and inserts a single quote Notes 1 The expression of precedence 1000 i e belonging to syntactic category term 1000 which is written X Y denotes the term X Y in standard syntax 2 The parenthesized expression belonging to syntactic category term 0 CX denotes simply the term X 3 The curly bracketed expression belonging to syntactic category term 0 X denotes the term X in standard syntax 4 Note that for example 3 denotes a number whereas 3 denotes a compound term which has the 1 ary funct
316. he atom Op is currently an operator of type Type and precedence Precedence Neither Op nor the other arguments need be instantiated at the time of the call i e this predicate can be used to generate as well as to test Chapter 7 Built In Predicates 125 break Invokes a recursive top level See Section 1 9 Nested page 16 This predicate is not available in Runtime Systems nor in Muse abort Aborts the current execution See Section 1 9 Nested page 16 In recursive calls to Prolog from C this predicate will return back to C instead In Muse will adjust the system to one worker save_program Fle save_program File Goal The system saves the program state into file File When the program state is restored Goal is executed Goal defaults to true See Section 1 10 Saving page 17 Requires Muse to be adjusted to one worker restore File The system is returned to the program state previously saved to file File with start up goal Goal restore 1 may succeed fail or raise an exception depending on Goal See Section 1 10 Saving page 17 Requires Muse to be adjusted to one worker reinitialise This predicate can be used to force the reinitialization behavior to take place at any time When SICStus Prolog is reinitialized it e calls any user defined C function pointed at by SP_reinit_hook see Section 8 7 Hooks page 150 e calls version O to write banners 96 e looks for a file sicstusrc or si
317. he bitwise disjunction of the integers X and Y X Y The value is the bitwise exclusive or of the integers X and Y NCX The value is the bitwise negation of the integer X X Y The value is the integer X shifted left by Y places X gt gt Y The value is the integer X shifted right by Y places X A list of just one number X evaluates to X Since a quoted string is just a list of integers this allows a quoted character to be used in place of its character code e g A behaves within arithmetic expressions as the integer 65 Chapter 7 Built In Predicates 95 SICStus Prolog also includes an extra set of functions listed below These may not be supported by other Prologs All trigonometric and transcendental functions take float arguments and deliver float values The trigonometric functions take arguments or deliver values in radians abs X The value is the absolute value of X gcd X Y The value is the greatest common divisor of the two integers X and Y min X Y The value is the lesser value of X and Y max X Y The value is the greater value of X and Y msb X The value is the most significant bit position of the integer X It is equivalent to but more efficient than integer log 2 X round X The value is the float that is the closest integral value to X If X is exactly half way between two integers it must be rounded to the closest even integral value truncate X The value is the float that is the closest in
318. he following piece of C code illustrates these facilities The function signal init installs the function signal handler as the primary signal handler for the signals USR1 and USR2 That function invokes the predicate prolog handler 1 as the actual signal handler passing the signal number as an argument to the predicate SP pred ref event pred static int signal event signal no void signal no T SP term ref x SP new term ref int rc SP put integer x int signal no rc SP query event pred x if rc SP ERROR amp amp SP exception term x SP raise exception x Propagate any raised exception return rc static void signal_handler sig int sig SP_event signal_event void sig SP_reinstall_signal sig signal_handler SP_continue void signal_init event pred SP_predicate prolog_handler 1 144 SICStus Prolog SP_signal SIGUSR1 signal handler SP_signal SIGUSR2 signal handler 8 4 4 Exception Handling in C When an exception has been raised the functions SP_query SP_query_cut_fail and SP_ next_solution return SP_ERROR To access the exception term the argument of the call to raise_exception 1 which is asserted when the exception is raised the function SP_exception_ term is used As a side effect the exception term is retracted so if your code wants to pass the exception term back to Prolog it must use the SP_raise_exception function b
319. he method is found If Msg is a variable the goal is translated to objects call super Myself Msg Super Super which expands Msg and performs otherwise the same actions as call super exp 3 Chapter 32 Prolog Objects 347 super lt Msg is translated to objects call_super_exp Myself Msg Self Myself Super if Msg is a non variable call_super_exp 3 searches the supers of Myself Super is bound to the super object where the method is found If Msg is a variable the goal is translated to objects call_super Myself Msg Self Super which expands Msg and performs otherwise the same actions as call_super_exp 3 Obj Msg Tf Msg is non variable this is translated to Obj Msg Obj Obj Otherwise it is translated to objects call_object Obj Msg Obj Obj lt Msg Tf Msg is non variable this is translated to Obj Msg Self Obj Otherwise if Msg is a non variable it is translated to functor Obj O O Msg Self Obj Otherwise it is translated to objects call_object Obj Msg Self self lt Msg self Msg Msg are all translated like Self Msg Module Goal is translated to Module Goal Goal is translated to Src Goal where Src is the source module To illustrate the expansion consider the object history_point directives all executed in the history_point module objects create_object history_point point 1 attributes 3 display 3 move 4 new 4 print history 3 super 4 0
320. he standard error stream This allows you to trace programs while they are performing file I O The basic format is as follows S3 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 followed by the constraints matching the heads The final is the prompt indicating that you should type in one of the debug options see Section 31 4 5 CHR Debugging Options page 320 31 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 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 Retu
321. he tasks are ordered by latest start time ect The tasks are ordered by earliest completion time lct The tasks are ordered by latest completion time first est the default and last 1ct can be good heuristics 30 5 Statistics Predicates The following predicates can be used to get execution statistics fd_statistics Key Value This allows a program to access execution statistics specific to this solver General statistics about CPU time and memory consumption etc is available from the built in predicate statistics 2 For each of the possible keys Key Value is unified with the current value of a counter which is simultaneously zeroed The following counters are maintained See Sec tion 30 7 The Constraint System page 283 for details of what they all mean resumptions The number of times a constraint was resumed Chapter 30 Constraint Logic Programming over Finite Domains 283 entailments The number of times a dis entailment was detected by a constraint prunings The number of times a domain was pruned backtracks The number of times a contradiction was found by a domain being wiped out or by a global constraint signalling failure Other causes of backtrack ing such as failed Prolog tests are not covered by this counter constraints The number of constraints created fd_statistics Displays on the user_error stream a summary of the above statistics All counters are zeroed 30 6 Answer Constraints By def
322. hed the head of the clause containing the cut and caused the clause to be activated In other words the cut operation commits the system to all choices made since the parent goal was invoked and causes other alternatives to be discarded The goals thus rendered determinate are the parent goal itself any goals occurring before the cut in the clause containing the cut and any subgoals which were executed during the execution of those preceding goals For example member X X _ member X L member X L This predicate can be used to test whether a given term is in a list E g member b a b c returns the answer yes The predicate can also be used to extract elements from a list as in member X d e f With backtracking this will successively return each element of the list Now suppose that the first clause had been written instead Chapter 2 The Prolog Language 37 member X X _ In this case the above call would extract only the first element of the list d On backtracking the cut would immediately fail the whole predicate RPS ps ls qe gt er eas oer This is equivalent to x if p then q else r in an Algol like language It should be noticed that a cut discards all the alternatives since the parent goal even when the cut appears within a disjunction This means that the normal method for eliminating a disjunction by defining an extra predicate cannot be applied to a disju
323. hemes Its intended use is to generate hash values for terms that will be used with first argument clause indexing yielding compact and efficient multi argument or deep argument indexing term variables Term Variables Variables is the set of variables occurring in Term unify with occurs check X Y ISO True if X and Y unify to a finite acyclic term Runs in almost linear time acyclic term X True if X is finite acyclic Runs in linear time cyclic term X True if X is infinite cyclic Runs in linear time Chapter 18 Ordered Set Operations 207 18 Ordered Set Operations This package defines operations on ordered sets Ordered sets are sets represented as lists with the elements ordered in a standard order The ordering is defined by the lt family of term comparison predicates and it is the ordering produced by the built in predicate sort 2 see Section 7 3 Term Compare page 97 To load the package enter the query use_module library ordsets is ordset Set Set is an ordered set list to ord set List Set Set is the ordered representation of the set denoted by the unordered representation List Example list to ord set p r o 1 0 gl l P P g 1 0 p r E yes ord add element Set1 Element Set2 Set2 is Set1 with Element inserted in it preserving the order Example ord add element a c d e f b N N a b c d e f yes ord del element Se
324. hes by its search rule a clause whose head matches Gj Matching is done by the unification algorithm see Robinson 65 which computes the most general unifier mgu of Gj and H The mgu is unique if it exists If a match is found the current query is reduced to a new query Gl Gj 1 Bl Bm Gj l Gn mgu and a new cycle is started The execution terminates when the empty query has been produced If there is no matching head for a goal the execution backtracks to the most recent successful match in an attempt to find an alternative match If such a match is found an alternative new query is produced and a new cycle is started In SICStus Prolog as in other Prolog systems the search rule is simple search forward from the beginning of the program The computation rule in traditional Prolog systems is also simple pick the leftmost goal of the current query However SICStus Prolog and other modern implementations have a somewhat more complex computation rule pick the leftmost unblocked goal of the current query A goal can be blocked on one ore more uninstantiated variables and a variable may block several goals Thus binding a variable can cause blocked goals to become unblocked and backtracking can cause currently unblocked goals to become blocked again Moreover if the current query is Gl Gj1 Gj qs Gn where Gj is the first unblocked goal and matching Gj against a clause head causes sever
325. hically 2 l Q 1 2 3 The convex hull program directly corresponds to the mathematical definition of the 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 quantifier elimination is a compu tationally expensive operation and therefore this program is only useful as a benchmark for the projector and not so for the intended purpose 264 SICStus Prolog 29 6 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 A4 1 _ C 1 distinct squares distinct squares B C B gt 0 outof C B distinct_squares C outof DM outof B1 C l B B Bi note disequation outof C B filled_zone V L WIL CO CO V W V gt 0 filled_zone VIL L3 BIC C2 V lt 0 placed_square B L L1 filled_zone Li L2 C C1 Vb V B filled_zone Vb B L2 L3 C1 C2 placed_square B H HO H
326. hich case it is written via write 2 In particular the debugging package prints the goals in the tracing messages and the top level prints the final values of variables Thus you can vary the forms of these messages if you wish Note that on lists L 1 1 print 2 will first give the whole list to user portray 1 but if this fails it will only give each of the top level elements to user portray 1 That is user portray 1 will not be called on all the tails of the list Same as write_term Stream Term portrayed true numbervars true portray Term user portray Term A hook predicate This should either print the Term and succeed or do nothing and fail In the latter case the default printer write 1 will print the Term Chapter 7 Built In Predicates 83 portray_clause Clause portray_clause Stream Clause Writes the clause Clause onto Stream exactly as listing 0 1 would have writ ten it Same as write term Stream Term quoted true numbervars true indented true followed by a period and a newline removing redundant module prefixes and binding variables to terms of the form VAR N yielding friendlier variable names write term Term Options ISO write_term Stream Term Options ISO Same as write 1 2 etc with a list of options to provide extra control This pred icate in fact subsumes the above output predicates except portray clause 1 2 which additionally prints a period and a new
327. his is useful for making a directed graph undirected top_sort WeightedGraph Sorted Finds a topological ordering of a WeightedGraph and returns the ordering as a list of Sorted vertices Fails iff no ordering exists i e iff the graph contains cycles Takes O N 2 time max path V1 V2 WeightedGraph Path Cost Path is a maximum cost path of cost Cost from V1 to V2 in WeightedGraph there being no cyclic paths from V1 to V2 Takes O N 2 time min_path V1 V2 WeightedGraph Path Cost Path is a minimum cost path of cost Cost from V1 to V2 in WeightedGraph Takes O N 2 time min_paths Vertex WeightedGraph Tree Tree is a tree of all the minimum cost paths from Vertex to every other vertex in WeightedGraph This is the single source minimum cost paths problem path Vertex WeightedGraph Path Given a WeightedGraph and a Vertex of WeightedGraph returns a maximal Path rooted at Vertex enumerating more paths on backtracking Chapter 24 Weighted Graph Operations 227 reduce WeightedGraph Reduced Reduced is the reduced graph for WeightedGraph The vertices of the reduced graph are the strongly connected components of WeightedGraph There is an edge in Reduced from u to v iff there is an edge in WeightedGraph from one of the vertices in u to one of the vertices in v reachable Vertex WeightedGraph Reachable Given a WeightedGraph and a Vertex of WeightedGraph returns the set of vertices that
328. i in gt 2 5 Linear arithmetic constraints maintain at least interval consistency and their reified versions detect at least interval entailment and disentailment see Section 30 7 The Constraint System page 283 The following constraints are among the library constraints that general arithmetic constraints compile to They express a relation between a sum or a scalar product and a value using a dedicated algorithm that avoids creating any temporary variables holding intermediate values If you are computing a sum or a scalar product it can be much more efficient to compute lists of coefficients and variables and post a single sum or scalar product constraint than to post a sequence of elementary constraints 276 SICStus Prolog sum Xs RelOp Value where Xs is a list of integers or domain variables RelOp is a relational symbol as above and Value is an integer or a domain variable True if Xs RelOp Value Cannot be reified scalar_product Coeffs Xs RelOp Value where Coeffs is a list of length n of integers Xs is a list of length n of integers or domain variables RelOp is a relational symbol as above and Value is an integer or a domain variable True if Coeffs Xs RelOp Value Cannot be reified 30 3 2 Membership Constraints domain Variables Min Max where Variables is a list of domain variables or integers Min is an integer or the atom inf minus infinity and Max is an integer or the
329. i Sern ra tee Se a ad ES 80 term reference aosi igneoen i er a EAEE 127 427 term compound coc 28 term Cyclic us iere alee a Rae EF E EA 36 81 83 term indexed etsera etr tede eee eee eee ee 236 berm layout oc iom mE TR PERS 81 term mutable area a eee eee 113 TOT IG iF denote oie het tees ce Mei Ub WOR Sead ch adiu 205 top level oa ridad ito O ees 8 tracing graphical rsss iyo nini e En E EEEN 44 TEGES eor thks oh eii aT AAE eene Ih aan te DLA GRENE A 219 type in module 0 eese 47 107 U USADA ra a id te AU bee baute 221 undefined predicate 00 15 103 106 UNICA ays 6 Sete ss eek cee ee eee MEAG aS 35 Unit clause io er LOB rer 30 unweighted graphs isses 221 A ee pereo T Tecos Tad adutoo que deci b Me dde 12 V yara blee or e Kreta PEE etae pe 27 28 variable domain 0 ik piin E a 272 variable instance eee eee 351 variables attributed 00 eee eee ee eee 193 Visandor tracing ise ebur er e ete s 45 volatile declaration esses eese esses 55 volatile predicate cece eee eee ee eee eee 55 voluntary suspension 0 02 eee eee eee 44 W WAMixeEovbwur ifm pare tate RE ck giae Na 1 43 weighted graphs arressegar e eie pene bue pen 225 WOT ADU oe heete thee ivan witch bua EE ideo Sender toga 225 WOPR ce web ses er rona VER URKCPREE Cinema QE ced 43 work speculative lssseeseeese esee 44
330. iable for the query connected Stockholm Orebro X X the following Java code will do it for us to new SPTerm sp Orebro from new SPTerm sp Stockholm way new SPTerm sp putVariable 6 Now it is time to make the query As in the C Prolog interface there are three ways of making a query query pred args This method is useful if you are only interested in finding the first solution to a goal In the case of connected 4 this is not the case there are more than one solution queryCutFail pred args This method is useful if you are only interested in the side effects of the query As query O it only finds the first solution and then it cuts away all other solutions and fails openQuery pred args This method is useful when you are interested in some or all solutions to the query Since the connected 4 may give us multiple solution this is what we will use SPQuery query query sp openQuery pred new SPTerm from to way way 3 while query nextSolution System out println way toString The openQuery method returns a reference to the query an object of the SPQuery class To obtain solutions the method nextSolution is called with no ar guments nextSolution returns true as long as there are more solutions the example above will print the value of way until there are no more solutions 9 5 Jasper Package Class Reference Detailed documentation of the classes in the jasper pa
331. ic Declarations page 54 e the atom multifile for predicates that have been declared multifile see Sec tion 5 2 1 Multifile Declarations page 54 e theatom volatile for predicates that have been declared volatile see Section 5 2 3 Volatile Declarations page 55 e one or more terms block Term for predicates that have block declarations see Section 5 2 4 Block Declarations page 55 e the atom exported or terms imported_from ModuleFrom for predicates ex ported or imported from modules see Chapter 4 Module Intro page 47 e the term meta_predicate Term for predicates that have meta predicate decla rations see Section 4 6 Meta Decl page 50 e in Muse only the atom sync for predicates that perform side effects that must be synchronized to preserve standard semantics Chapter 7 Built In Predicates 105 e in Muse only the atom parallel for predicates that may be executed in parallel This predicate can be used to enumerate all existing predicates and their properties through backtracking current module Module Module is a module in the system It can be used to backtrack through all modules present in the system current module Module File Module is the module defined in File module Module The type in module is set to Module prolog_flag FlagName OldValue New Value OldValue is the value of the Prolog flag FlagName and the new value of FlagName is set to New Value The possible Pro
332. icate 00 0 e cee eee eee eee 46 Character 1 O 2 csse ere re tn iaer cee cee RE Eg 87 character Seti aii 10 398 CHOICEPOINGE lt 4 cases eh pane as seein se A qeu er ek pendet 43 CHR control flow model 0 00 317 CHR debugging messages 0 000005 320 CHR debugging options 000 320 423 CHR debugging predicates ssueuuuueu 317 CHR spy points 0 cece eee 319 CAUSA tcc Ue a 30 clause g arded i iiie ees 179 COMA di imr ees ge ERIT Te PR AIO RELON vee 8 command line argumentS ooooocoooconccccncroco T communication eire rer o EEEE en 231 Comparing TELS Lese d Rd Meter Ra ees 97 compilation 5 3 Sub SPD MSN tide 73 COMPING ei o Cue erc Miata pte een nN Wea Eee ead 7 compound term 0 eee eee 27 28 computation rule 0 cee eee 35 conformance ANSI 0c cece eee eee eee 6 127 considerations for feompile 00 58 consistent SLOT ic wea ae E bbb rc A Eee te 283 constant cui uiu A bruto Eas 27 CONSULAIN Utes hes Sarasa hss hare AA AAE 272 constfamt Stores iue SP tees UIS P auis 283 constraint global 0 0 0 0c cece cece eee ee 285 cons lting opere abe te a OPE ees 7 11 52 73 context DIrectOEy da ree ERR eria 108 context Files Leere dada idee ebd 108 context Module 0 2 eee eee eee 108 contradictory store 0 cece eee eee 283 CONVETSION
333. id up to the request for the next solution They also become invalid when the query is closed A new SP term ref whose value is is created by calling SP term ref SP new term ref void The value of the SP term ref to is set to the value of the SP term ref from by calling SP_put_ term to from The previous value of to is lost void SP put term SP term ref to SP term ref from Each Prolog atom is represented internally by a unique integer represented in C as an unsigned long This mapping between atoms and integers depends on the execution history Certain func tions require this representation as opposed to an SP pred ref It can be obtain by a special argument type declaration when calling C from Prolog by calling SP_get_atom or by looking up a string s in the Prolog symbol table by calling SP atom from string s unsigned long SP atom from string char s The print name of a Prolog atom a can be obtained by calling char SP string from atom unsigned long a The print name length of a Prolog atom a can be obtained by calling Chapter 8 Mixing C and Prolog 137 int SP_atom_length unsigned long a Same as strlen SP_string_from_atom a but runs in O 1 time Prolog atoms and the space occupied by their print names are subject to garbage collection when the number of atoms has reached a certain threshold under the control of the agc_margin Prolog flag see Section 7 6 State Info page 104 or when the atom garb
334. if there exists an X such that P is true Same as P X 0 P X 1 P Q Sameas P amp Q P Q SameasP Q P lt Q Same as P Q P gt Q Same as P Q P Q Same as P Q P gt Q Same as P Q card Is Es True if the number of true expressions in Es is a member of the set denoted by Is Symbolic constants Prolog atoms denote parametric values and can be viewed as all quantified variables whose quantifiers are placed outside the entire expression They are useful for forcing certain variables of an equation to be treated as input parameters 242 SICStus Prolog 28 1 Solver Interface The following predicates are defined sat Expression Expression is a Boolean expression This checks the consistency of the expression wrt the accumulated constraints and if the check succeeds tells the constraint that the expression be true If a variable X occurring in the expression is subsequently unified with some term T this is treated as a shorthand for the constraint sat X T taut Expression Truth Expression is a Boolean expression This asks whether the expression is now entailed by the accumulated constraints Truth 1 or whether its negation is entailed by the accumulated constraints Truth 0 Otherwise it fails labeling Variables Variables is a list of variables The variables are instantiated to a list of Os and 1s in a way that satisfies any accumulated constraints Enumerates all soluti
335. ight sockets provides an interface to system calls for manipulating sockets linda client linda server provides an implementation of the Linda concept for process communication db provides storage and retrieval of terms on disk files with user defined multiple indexing clpb provides constraint solving over Booleans clpq clpr provides constraint solving over Q Rationals or R Reals clpfd provides constraint solving over Finite Integer Domains chr provides Constraint Handling Rules objects provides the combination of the logic programming and the object oriented program ming paradigms 188 SICStus Prolog gcla is a specification tool that is based on Generalized Horn Clause Language a general ization of Prolog tcltk An interface to the Tcl Tk language and toolkit gauge is a profiling tool for Prolog programs with a graphical interface based on tcltk charsio defines I O predicates that read from or write to a list of character codes jasper An interface to the Java language flinkage is a utility program for generating glue code for the Foreign Language Interface when building statically linked Runtime Systems or Development Systems timeout provides a way of running goals with an execution time limit xref provides a cross reference producer for debugging and program analysis To load a library package Package you will normally enter a query use module library Package A library package normally con
336. ign 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 270 SICStus Prolog 29 9 1 2 Partial Evaluation Compilation 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 constraints 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 dump 3 call_residue 2 for the expansion of 1 via hook predicate user goal expansion 3 29 9 1 3 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 works as expected clp r A lt 10 assert p A A lt 10 0 yes clp r p X X lt 10 0 29 9 2 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 lt christian ai univie ac at gt
337. ike ensure_loaded 1 and imports the predicates in Imports If any of these are not public a warning is issued Imports may also be set to the atom all in which case all public predicates are imported Same as load_files File if changed imports Imports use module Module File Imports This is equivalent to use module 2 with the addition that Module is unified with the loaded module after the loading fcompile Files Compiles the source file or list of files specified by Files If Files are prefixed by a module name that module name will be used for module name expansion during the compilation see Section 5 3 Considerations page 58 The suffix p1 is added to the given filenames to yield the real source filenames The compiled code is placed on the object file or list of files formed by adding the suffix ql to the given filenames This predicate is not available in Runtime Systems source file File File is the absolute name of a source file currently in the system source file Head File source file Head File Head is the most general goal for a predicate loaded from File require PredSpecOrSpecs PredSpecOrSpecs is a predicate spec or a list or a conjunction of such The predicate will check if the specified predicates are loaded and if not will try to load or import them using use_module 2 The file containing the predicate definitions will be located in the following way e The directories
338. ilable in Runtime Systems listing listing Specs Lists the interpreted predicate s specified by Specs or all interpreted predicates in the type in module Any variables in the listed clauses are internally bound to ground terms before printing If this causes any blocked goals to be executed the behavior is undefined load Files Loads object file s Files load files Files load files Files Options Loads source or object file s Files obeying Options 386 SICStus Prolog load_foreign_files ObjectFiles Libraries Hookable links object files ObjectFiles into Prolog Obsolete use link foreign resource 6 and load foreign resource 1 instead load foreign resource Resource Loads foreign resource Resource into Prolog unload foreign resource Resource Unloads foreign resource Resource from Prolog meta predicate Specs Not a built in predicate meta predicate declaration method expansion Methodl Object Method2 user method expansion Method Object Method2 A hook predicate defines transformations on Prolog Object methods mode Specs Not a built in predicate mode declaration module 4 Module Sets the type in module to Module see Section 4 1 Basic Concepts page 47 module 4 Module Export List module Module ExportList Options Not a built in predicate module declaration multifile Specs Not a built in predicate multifile declaration muse_flag FlagName
339. imination 259 29 5 1 Variable Ordering 0 0 cece cece ee 260 29 5 2 Turning Answers into Terms 0045 261 29 5 3 Projecting Inequalities 0 0 eee eee eee 261 29 6 Why Disequations eeeeeee me 264 29 SyMtactic Sugar bs he ashe ne aed ea al 265 29 7 1 Monash Examples lessen 266 29 7 1 1 Compatibility NotesS 0oooooommmmo o 267 29 8 A Mixed Integer Linear Optimization Example 268 29 9 Implementation Architecture 0 06 cece cee eese 269 29 9 1 Fragments and Bits 0 0 eee eee eee 269 29 9 1 1 Rational 2 5 re Dre ec dtes 269 29 9 1 2 Partial Evaluation Compilation 270 29 9 1 3 Asserting with ConstraintS 270 20 9 2 Bugs dere e HERE da ne Pas as atte 270 30 Constraint Logic Programming over Finite Domains Jac atest er cada adt eee pt eite 271 30 1 Introduction ekle o b RR PERI EE T pn ord 271 Referencing this Software 2 0 ce eee ee eee 271 Acknowledgments eese 272 30 2 Solver Interface ria eT Bk bee eee ae eee 272 30 2 1 Posting Constraints 0 cee ee e 273 30 2 2 A Constraint Satisfaction Problem 273 30 2 3 Reified Constraints 0 cece eee eee eens 274 30 3 Available Constraints 0 00 cee cece hne 275 30 3 1 Arithmetic Constraints 0 000 eese 275 30 3 2 Membership Constraints
340. in the method to appropriate values given by the receiver The receiver may be the object where the method is defined or any of its subs In order to service these calls a clause of fix param 2 is generated for each ancestor having parameters Such a clause may be regarded as the collapsed chain of super 1 2 definitions leading up to the ancestor The call objects object class Class Object serves to pick up the class 1 attribute if Object is an instance otherwise Class is unified with Object The following trace illustrates how parameters are transfered G N5OOCCOgBS PB 5UONNTA A N l e NWUWUUABUOUNBEe gt li red_circle 2 5 area A Call Call Call Call Exit Exit Call Exit Exit Exit red_circle 2 5 area _A ellipse _ _ _ area _A red_circle 2 5 red_circle 2 5 red_circle _ fix_param ellipse _B _ _ red_circle 2 5 objects object_class red_circle _B red_circle 2 5 objects object_class red_circle 2 5 red_circle 2 5 red_circle _ fix_param ellipse 2 5 2 5 red red_circle 2 5 _A is 2 5 2 5 3 14159265 19 6349540625 is 2 5 2 5 3 14159265 ellipse _ _ _ area 19 6349540625 red_circle 2 5 red_circle 2 5 red_circle 2 5 area 19 6349540625 19 6349540625 350 SICStus Prolog 32 10 Examples 32 10 1 Classification of Birds This example illustrates how Prolog object can be used in classification of certain concepts This style is common in expert system
341. inary Tree from List where get_label K Tree Lab iff Lab is the Kth element of List map_tree Pred OldTree NewTree Old Tree and NewTree are binary trees of the same shape and Pred Old New is true for corresponding elements of the two trees put_label I OldTree Label NewTree Constructs NewTree which has the same shape and elements as OldTree except that the I th element is Label put label I OldTree Label NewTree Label Constructs NewTree which has the same shape and elements as OldTree except that the I th element is changed from OldLabel to NewLabel tree_size Tree Size Calculates as Size the number of elements in the Tree tree_to_list Tree List Is the converse operation to list_to_tree 2 Any mapping or checking operation can be done by converting the tree to a list mapping or checking the list and converting the result if any back to a tree 220 SICStus Prolog Chapter 23 Unweighted Graph Operations 221 23 Unweighted Graph Operations Directed and undirected graphs are fundamental data structures representing arbitrary relation ships between data objects This package provides a Prolog implementation of directed graphs undirected graphs being a special case of directed graphs An unweighted directed graph ugraph is represented as a list of vertex neighbors pairs where the pairs are in standard order as produced by keysort with unique keys and the neighbors of each vertex are al
342. ince 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 be achieved with corresponding pragmas see Section 31 3 5 CHR Pragmas page 311 The remaining options are meant for CHR implementors only option flatten on off option rule_ordering canonical heuristic Chapter 31 Constraint Handling Rules 313 option simpagation_scheme single multi option revive_scheme new old option dead_code_elimination on off 31 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 enume
343. ing Prolog terms and for creating and manipulating SP term refs e The Prolog system may call C predicates which may call Prolog back without limits on recur sion e Possibility to create stand alone applications Runtime Systems e Possibility to create user defined Prolog streams e Functions to read and write on Prolog streams from C e Possibility to install interrupt handlers that can safely call Prolog e User hooks that can be used to perform user defined actions on a number of occasions e g before reading a character from the standard input stream upon reinitialization etc 8 1 Notes ANSI Conformance Throughout this chapter void in the function definitions may be changed to char on non ANSI conforming C compilers The SP_PATH variable It is normally not necessary to set this environment variable but its value will be used at runtime if no explicit boot path is given when initializing a Runtime or De velopment System In this chapter the environment variable SP PATH is used as a shorthand for the SICStus Prolog installation directory whose default UNIX location is usr local lib sicstus37 See Section 1 1 2 Environment Variables page 10 Definitions and declarations Type definitions and function declarations for the interface are found in the header file lt sicstus sicstus h gt 128 SICStus Prolog Error Codes The value of many support functions is a return code which is one of SP_SUCCESS for s
344. ing backwards up the code looking for choice points Exception This arrow represents an exception which was raised in the initial goal either by a call to raise_exception 1 or by an error in a built in predicate See Section 7 5 Exception page 101 Control now passes out of the Exception port of the descendant box and the systems continues to pass the exception to outer levels Textually we move Chapter 6 Debugging 61 back to the code which called this predicate and keep moving backwards up the code looking for a call to on_exception 3 In terms of this model the information we get about the procedure box is only the control flow through these five ports This means that at this level we are not concerned with which clause matches and how any subgoals are satisfied but rather we only wish to know the initial goal and the final outcome However it can be seen that whenever we are trying to satisfy subgoals what we are actually doing is passing through the ports of their respective boxes If we were to follow this then we would have complete information about the control flow inside the procedure box Note that the box we have drawn round the predicate should really be seen as an invocation box That is there will be a different box for each different invocation of the predicate Obviously with something like a recursive predicate there will be many different Calls and Exits in the control flow but these will be for different invocation
345. ing character input from the standard input stream is C ttyget0 C The next character input from the standard input stream is C ttynl Outputs a new line on the standard output stream ttyput C The next character output to the standard output stream is C ttyskip C Skips characters from the standard input stream until after character C 392 SICStus Prolog ttytab N Outputs N spaces to the standard output stream unknown OldState NewState Changes action on undefined predicates from OldState to NewState not available in Runtime Systems unknown predicate handler Goal Module NewGoal user unknown predicate handler Goal Module NewGoal A hook predicate Defines an alternative goal to be called in place of a call to an unknown predicate update_mutable Datum Mutable Updates the current value of the mutable term Mutable to become Datum use_module Files Loads the module file s Files if necessary and import all public predicates use module File Imports Loads the module file File if necessary and imports the predicates in Imports use module Module File Imports use module Module File Imports Equivalent to use modu1e 2 plus unifies Module to the module defined by the file user help user user help A hook predicate tells help 0 what to do var X X iscurrently uninstantiated version Displays introductory and or system identification messages not available in
346. ingle sentence 52 SICStus Prolog 5 1 Predicates which Load Code To consult a program issue the directive consult Files where Files is either the name of a file including the file user or a list of filenames instructs the processor to read in the program which is in the files For example consult dbase extras pl user When a directive is read it is immediately executed Any predicate defined in the files erases any clauses for that predicate already present If the old clauses were loaded from a different file than the present one the user will be queried first whether s he really wants the new definition However if a multifile declaration see Section 5 2 Declarations page 53 is read and the corresponding predicate exists and has previously been declared as multifile new clauses will be added to the predicate rather than replacing the old clauses If clauses for some predicate appear in more than one file the later set will effectively overwrite the earlier set The division of the program into separate files does not imply any module structure any predicate can call any other see Chapter 4 Module Intro page 47 consult 1 used in conjunction with save program 1 2 and restore 1 makes it possible to amend a program without having to restart from scratch and consult all the files which make up the program The consulted file is normally a temporary patch file containing only the ame
347. integers and Options is a list of search options True if an assignment of the variables can be found which satisfies the posted constraints The search options control the order in which variables are selected for assignment variable choice heuristic the way in which choices are made for the selected variable value choice heuristic and whether all solutions or a single optimal solution should be found The search options are divided into four groups One option may be selected per group Finally the number of assumptions choices made during the search can be collected The following options control the order in which the next variable is selected for as signment None of these methods will select a variable with an unbounded domain Thus labeling 2 may succeed with such variables still unassigned Chapter 30 Constraint Logic Programming over Finite Domains 281 leftmost The leftmost variable is selected This is the default min The leftmost variable with the smallest lower bound is selected max The leftmost variable with the greatest upper bound is selected ff The first fail principle is used the leftmost variable with the smallest do main is selected ffc The most constrained heuristic is used a variable with the smallest domain is selected breaking ties by a selecting the variable that has the most constraints suspended on it and b selecting the leftmost one The following options control the way in which choices a
348. inv_e_series Term SO _ Err Sum abs Term lt Err SO Sum inv_e_series Term SO N Err Sum Ni is N 1 Termi Term N S1 Term1 S0 inv e series Termi S1 Ni 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 28423342907 44221392610955845565494 3708750229467761730471738895197792271346693089326102132000338192 0131874187833985420922688804220167840319199699494193852403223700 5853832741544191628747052136402176941963825543565900589161585723 4023097 417605004829991929283045372355639145644588174733401360176 9953973706537 274133283614740902771561159913069917833820285608440 3104966899999651928637634656418969027076699082888742481392304807 9484725489080844360397606199771786024695620205344042765860581379 353829045120832212989806997810797 122687316087 2046731879753034549 3130492167474809196348846916421782850086985668680640425192038155 490286329835 1349469211627292865440876581064873866786120098602898 8799130098877372097360065934827751120659213470528793143805903554 7928682131082164366007016698761961066948371407368962539467994627 1374858249110795976398595034606994740186040425117101588480000000 258 SICStus Prolog 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000
349. ion can be used to raise a fault For example it can be used in a signal handler for SIGSEGV to prevent the program from dumping core in the event of a segmentation violation Runtime Systems have no predefined signal handling void SP raise fault char message 8 8 3 Creating the Executable This describes how to create a Runtime System with a set of statically linked foreign resources For the SICStus library modules containing C code such linked foreign resources already exist in SP_PATH library For user foreign code you must first create linked foreign resources for them A utility command is provided for the generation of such systems This command located in SP_PATH bin is configurable as described in the Release Notes spmkrs help S Executable c SourceFiles o ObjectFiles 1 Libraries r Resources Generates a Runtime System with any foreign resources mentioned in Resources stat ically linked The resources must be created with the static option Note however that a statically linked dynamic resource is not in general statically linked from the operating system s point of view It must therefore be accessible at runtime as well as at build time Compiles SourceFiles and links the resulting object files with ObjectFiles Libraries and the foreign resources to produce Executable The main program of the Runtime System must be provided by SourceFiles or Object Files Chapter 8 Mixing C and Prolog
350. ion into this distribution was kindly permitted by Roland Yap 248 SICStus Prolog 29 2 Solver Interface Until rational numbers become first class citizens in SICStus Prolog 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 You can also load both modules but the exported predicates listed below will name clash see Sec tion 4 4 Importation page 49 You can avoid the interactive resolution dialog if the importation is skipped e g via use module library clpq use_module library clpr 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 Section 29 5 1 Variable Ordering page 260 The approximative nature of floating point numbers may
351. ion stops when either control comes back to this predicate or a spy point is reached No debugging information is being collected while quasi skipping An integer argument can be supplied as for skip retry can be used at any of the four ports although at the Call port it has no effect It transfers control back to the Call port of the box This allows you to restart an invocation when for example you find yourself leaving with some weird result The state of execution is exactly the same as when you originally called unless you use side effects in your program i e asserts etc will not be undone When a retry is performed the invocation counter is reset so that counting will continue from the current invocation number regardless of what happened before the retry This is in accord with the fact that you have in executional terms returned to the state before anything else was called If you supply an integer argument then this should denote an invocation number of an ancestral goal The system tries to get you to the Call port of the box you have specified It does this by continuously failing until it reaches the right place Unfortunately this process cannot be guaranteed it may be the case that the invocation you are looking for has been cut out of the search space by cuts in your program In this case the system fails to the latest surviving Call port before the correct one fail can be used at any of the four ports although a
352. ions 3 4 Visualization Tools The distribution provides two tools that enable one to obtain insight into the parallel behavior of his Prolog program These tools can help in understanding performance bugs situations in which a program is executing correctly but not as fast as anticipated due to an unforeseen restriction of the degree of parallelism in the program Once such restrictions are understood they can often be removed by changing the program resulting in greatly improved performance Both of these tools use log files that is they do not display graphics while the program is running but rather display the contents of a file that is created during program execution This method has several advantages e A significant log file can be retained and studied for a long time e The log file can be played far more slowly than the original program ran allowing careful and detailed study e The graphics tracing program need not run on the same machine as Muse itself In this manual we will not discuss the various graphics tracers in detail but rather we will leave the details of each to its own manual We will however describe how to collect the log files each one needs Chapter 3 Running Prolog in Parallel 45 3 4 1 Must The Must graphics tracing facility Karlsson 92 shows the Prolog search tree as it is expanded and contracted in parallel by Muse workers Having created a version of Muse with the Must tracing
353. ions on its use in Runtime Systems will be mentioned Function Prototypes Whenever this manual documents a C function as part of SICStus Prolog s foreign language inter face the function prototype will be displayed in ANSI C syntax ISO Compliance SICStus Prolog complies in spirit if not in detail with the Draft International Standard ISO IEC 13211 1 PROLOG Part 1 General Core In particular SICStus Prolog does not offer a strictly conforming mode which rejects uses of implementation specific features Minor deviations also concern e g the syntax the arithmetic functions and the error system To aid programmers who wish to write standard compliant programs built in predicates that have a counterpart in the ISO Prolog Standard are annotated with ISO in this manual where appropriate with a comment clarifying the difference between the SICStus and the prescribed ISO Prolog versions Chapter 1 How to Run Prolog 7 1 Howto Run Prolog SICStus Prolog offers the user an interactive programming environment with tools for incremen tally building programs debugging programs by following their executions and modifying parts of programs without having to start again from scratch The text of a Prolog program is normally created in a file or a number of files using one of the standard text editors The Prolog interpreter can then be instructed to read in programs from these files this is called consulting the file Alternatively
354. ions will be approximated with rationals The preci sion 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 256 SICStus Prolog 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 S R root N S R N1 is N 1 Si 8 2 1 8 root N1 S1 R It is known that this approximation converges quadratically which means that the number of correct 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 C clpqr examples root clp q root 3 R print decimal R 70
355. ips However it is sometimes useful to make exceptions trap to the debugger at the earliest opportunity instead The following predicate provides such a possibility error_exception Exception user error_exception Exception A hook predicate This predicate is called at all exception ports If it succeeds the debugger enters trace mode and prints an exception port message Otherwise the debugger mode is unchanged and a message is printed only in trace mode or if a spy point is reached and not during skips 70 SICStus Prolog Chapter 7 Built In Predicates 71 7 Built In Predicates It is not possible to redefine built in predicates An attempt to do so will give an error message See Pred Summary page 379 SICStus Prolog provides a wide range of built in predicates to perform the following tasks Input Output Reading in Programs Term and Goal Expansion Input and Output of Terms Character I O Stream I O Dec 10 Prolog File I O Arithmetic Comparison of Terms Control Error and Exception Handling Information about the State of the Program Meta Logic Modification of Terms Modification of the Program Internal Database Blackboard Primitives All Solutions Coroutining Debugging Execution Profiling Muse Support Miscellaneous The following descriptions of the built in predicates are grouped according to the above categoriza tion of their tasks 7 1 Input Output There are two sets of file manipulation predicate
356. is a bidirectional interface to the Tcl pronounced Tickle language and the Tk toolkit Tcl is an interpreted scripting language with many extension packages in particular the graphical interface toolkit Tk You can read about Tcl Tk in Ousterhout 94 or in various articles The articles and the Tcl Tk system can be found by anonymous FTP see the Release Notes for up to date information This file also contains information on how to include Tcl Tk extensions To load the package enter the query use module library tcltk 34 1 Prolog to Tcl To use Tcl you must create a Tcl interpreter object and send commands to it The following predicate executes a single Tcl command test command Command Result tcl new Interp tcl eval Interp Command Result tcl delete Interp The Tcl command and its arguments is specified in Command see Section 34 1 1 Command Format page 362 and the result will be returned as a string list of character codes in Result These are the predicates to use Tcl Tk from Prolog tcl new TclInterpreter Creates a new interpreter initializes it and returns a reference to it If you don t have a standard Tcl installation you can tell Tcl where to look for the initialization files by setting the environment variable TCL LIBRARY tcl delete TclInterpreter Deletes an interpreter and the memory used by it tcl eval TclInterpreter Command Result Lets TclInterpreter interpret the
357. is declaratively as Goals matching P are true and procedurally as Goals matching P are satisfied If the body of a clause is non empty the clause is called a non unit clause and is written in the form P Q R S where P is the head goal and Q R and S are the goals which make up the body We can read such a clause either declaratively as P is true if Q and R and S are true or procedurally as To satisfy goal P satisfy goals Q R and S A sentence with an empty head is called a directive see Section 1 4 Directives page 12 of which the most important kind is called a query and is written in the form P Q where P and Q are the goals of the body Such a query is read declaratively as Are P and Q true and procedurally as Satisfy goals P and Q Sentences generally contain variables Note that variables in different sentences are completely in dependent even if they have the same name 1 e the lexical scope of a variable is limited to a single sentence Each distinct variable in a sentence should be interpreted as standing for an arbitrary entity or value To illustrate this here are some examples of sentences containing variables with possible declarative and procedural readings 1 employed X employs Y X Any X is employed if any Y employs X To find whether a person X is employed find whether any Y employs X 32 SICStus Prolog 2 derivative X X 1 For any X the derivative of X with re
358. ise exception Exception is called and Exception matches Pattern the execution of ProtectedGoal abort Pattern is unified with a copy of Exception and Handler is called op Precedence Type Name Makes atom s Name an operator of type Type precedence Precedence open 4 FileName Mode Stream open FileName Mode Stream Options ISO Opens file FileName in mode Mode with options Options as stream Stream open null stream Stream Opens an output stream to the null device otherwise True parallel parallel Specs Not a built in predicate parallel declaration peek_char N peek char Stream N N is the character code of the next character peeked at from Stream or from the current input stream 388 SICStus Prolog phrase Phrase List phrase Phrase List Remainder Grammar rules The list List can be parsed as a phrase of type Phrase The rest of the list is Remainder or empty portray Term user portray Term A hook predicate tells print 1 what to do portray_clause Clause portray_clause Stream Clause Pretty prints Clause on the stream Stream or on the current output stream portray message Severity Message user portray_message 4Severity Message A hook predicate tells print message 2 what to do predicate property Head Prop predicate property Head Prop Head is the most general goal of a currently defined predicate that has the propert
359. isplay Term Displays the term Term on the standard output stream dynamic Specs Not a built in predicate dynamic declaration ensure loaded Files Compiles or loads the file s Files if need be erase Ref Erases the clause or record whose unique identifier is Ref error exception Exception user error exception Exception A hook predicate Exception is an exception that traps to the debugger if it is switched on expand term Terml Term2 The term Term1 is a shorthand which expands to the term Term2 fail false False fcompile Files Compiles file to file the clauses in text file s Files not available in Runtime Systems file search path Alias Expansion user file search path Alias Expansion A hook predicate telling how to expand Alias File file names fileerrors Enables reporting of file errors findall Template Goal Bag findall Template Goal Bag Remainder A prefix of Bag is the list of instances of Template such that Goal is provable The rest of Bag is Remainder or the empty list float X X is currently instantiated to a float flush output flush output Stream Flushes the buffers associated with Stream foreign CFunctionName Predicate foreign CFunctionName Language Predicate Hook predicates tell Prolog how to define Predicate to invoke CFunctionName foreign file ObjectFile Functions A hook predicate tells Prolog that foreign functions Fun
360. isses 369 freeze 2255 sc tees prp ecuPUNP DEOS Se UL 119 Irozen 2 4 eu M ure it erus 120 functor 3323 sks ei Die hae Dae bu 111 G garbage collect 0 isses eee eee 125 garbage collect atoms 0 esses 125 garbage collection statistics 2 option 109 gc prolog flag ica o 106 lo EL 125 gcmargin prolog flag sss 106 gc trace prolog flag oooooooococccccocco o 106 gcd 2 greatest common divisor 95 gen ASSOC A arbi hear REO Ped ther de 191 geni Iabel 3 ice wane dea S tute UE 219 generate flinkage 1 sse en 373 Pet Ala vio A e ios e Cose ER a Cis 88 Eet 2 uito rem co hates ee t RU e baer aga ERU RA 88 POtsassoC rm 191 get assoc b ci esee tuber E E re ede 191 get atts 2 ilii Mandel x bids 193 get default db l i ndisncEkRb uk b aes 237 get fromdeap 4 iini ui ies mer tise eeu ies 199 get label 43s reU a el Rabe eic 219 get mitable 2i mi u EE EEA enne 113 get_next_assoc 4 ret ue nnn 191 get_prev_assoc 4 0 h i neinean iE nE 192 A E E E EE 87 Bet0O 2 sesta baa duca EE AIE bald ae ER E LASTE ena 87 getrand 1 l p EE 213 global stack statistics 2 option 108 GLOBALSTKSIZE environment sss 10 goal expansion 3 0 cece cece eee 79 Sr ound 1 ih nt wie ein aa 110 H halt 0 ppt dA a ee Led 124 E ro PE EL ab eas cas 124 heap statistics 2 option 05 109 CAE AA heats ui M use been 1
361. itute of Technology Stockholm 1990 Heintze et al 87 N Heintze J Jaffar S Michaylov P Stuckey R Yap The CLP R Programmers Manual Monash University Clayton Victoria Australia Department of Computer Science 1987 Hermenegildo and Greene 90 M V Hermenegildo and K J Greene amp Prolog and its performance Exploiting In dependent And Parallelism Proceedings of the Seventh ICLP Jerusalem MIT Press 1990 Holzbaur 90 C Holzbaur Specification of Constraint Based Inference Mechanism through Extended Unification dissertation Dept of Medical Cybernetics amp AI University of Vienna 1990 Holzbaur 92 C Holzbaur A High Level Approach to the Realization of CLP Languages Proceed ings of the JICSLP92 Post Conference Workshop on Constraint Logic Programming Systems Washington D C 1992 Holzbaur 92 C Holzbaur Metastructures vs Attributed Variables in the Context of Extensible Unification in M Bruynooghe amp M Wirsing eds Programming Language Imple mentation and Logic Programming Springer Verlag LNCS 631 pp 260 268 1992 References 407 Holzbaur 94 C Holzbaur A Specialized Incremental Solved Form Algorithm for Systems of Linear Inequalities Austrian Research Institute for Artificial Intelligence Vienna TR 94 07 1994 Jaffar amp Michaylov 87 J Jaffar S Michaylov Methodology and Implementation of a CLP System in J L Lassez ed Logic Programming Proceedings of
362. ize the wait declarations of earlier versions of SICStus Prolog A declaration wait f 3 in the old syntax corresponds to block f 7 in the current 56 SICStus Prolog syntax See Section 10 5 6 Use Of Term Exp page 182 for a simple way to extend the system to accept the old syntax 5 2 5 Meta Predicate Declarations A declaration meta predicate MetaPredSpec MetaPredSpec where each MetaPredSpec is a mode spec informs the compiler that certain arguments of the declared predicates are used for passing goals To ensure the correct semantics in the context of multiple modules clauses or directives containing goals for the declared predicates may need to have those arguments module name expanded See Section 4 5 Meta Exp page 49 for details 5 2 6 Module Declarations A declaration module ModuleName ExportList Options where Export List is a list of predicate specs declares that the forthcoming predicates should go into the module named ModuleName and that the predicates listed should be exported See Section 4 3 Def Modules page 48 for details 5 2 7 Public Declarations A declaration public PredSpec PredSpec where each PredSpec is a predicate spec has no effect whatsoever but is accepted for compatibility reasons In some Prologs this declaration is necessary for making compiled predicates visible In SICStus Prolog predicate visibility is handled by the module system See Chapt
363. jre index html The rest of this chapter assumes that there is a Java installation with JNI support available 9 2 Calling Java from Prolog Java methods are called from Prolog much in the same way as C functions are called see Section 8 2 Calling C page 128 by creating a foreign resource When loaded this resource installs a set of predicates which are mapped onto Java methods and when invoked converts the Prolog arguments to the corresponding Java types before calling the Java method itself In fact a foreign resource as defined in Section 8 2 1 Foreign Resource page 128 is not language specific itself The language is instead specified in the second argument to the foreign 3 fact and it is possible to mix foreign C functions with foreign Java methods How a foreign resource is created in general is described in detail in Section 8 2 7 Creating the Linked Foreign Resource page 135 The following section s will focus on the Java specific parts of foreign resources 168 SICStus Prolog 9 2 1 Static and Dynamic Linking There is no support for static linking of foreign resources containing Java declarations since Java implementations usually do not support static linking 9 2 2 Declarating Java methods Java methods are declared similarly to C functions There are two major differences The first is how methods are identified It is not enough to simply use an atom as the C interface does Instead a term method 3 is introd
364. ks tk all events Process any event tk do one event O is equivalent to tk do one event 1 with all flags set If the tk dont wait flag is set and there is no event to handle the call will fail It is straight forward to define a predicate which handles all events in the queue and then returns tk do all events tk do one event tk do all events tk do all events tk do one event 0 1 is an interface to the C function TkDoOneEvent or TclDoOneEvent in later Tcl Tk versions 366 SICStus Prolog tk_next_event TclInterpreter Event tk next event ListOrBitmask TclInterpreter Event Processes events until there is at least one Prolog event associated with TclInterpreter Event is the term corresponding to the head of a queue of events strings representing terms stored from Tcl with the prolog event command see Section 34 2 Tcl to Prolog page 363 Only events associated with TclInterpreter are returned other events remain in the queue If there are no windows left the term will be returned This predicate does not correspond directly to any Tcl Tk C function tk main loop Passes control to Tk until all windows are gone There are basically two alternatives for invoking Prolog actions on user events The first is to directly call Prolog by means of the Tcl command prolog Tcl Tk must then be repeatedly invoked either by calling tk main loop O or using the option top level events possibly in conjunction
365. l and SICStus Prolog may be used without the user being aware of the module system at all Modules in SICStus Prolog can also be used for object oriented programming See Chapter 32 Obj Intro page 327 for details 4 1 Basic Concepts Each predicate in the Prolog system whether built in or user defined belongs to a module A predicate is generally only visible in the module where it is defined However a predicate may be imported by another module It is thereby made visible in that module too Built in predicates are visible in every module Predicates declared as public in a module declaration see below are exported Normally only public predicates may be imported by another module For any given goal the source module is the module in which the corresponding predicate must be visible Similarly for any given clause the source module of its head is the module into which the clause is loaded For goals occurring in a source file with a module declaration the source module is the declared module For goals occurring in a source file without a module declaration the source module is the module that the file is being loaded into For goals typed at the top level the source module is the type in module The type in module is by default the user module but may be changed by the built in predicate module 1 The other predefined module is the prolog module where all the built in predicates reside The exported built in predicates are auto
366. l and that comments with three 4 are never changed when indenting prolog indent mline comments flag Set to nil to prevent indentation of text inside comments Defaults t prolog object end to 0 flag Set to nil to indent the closing of an object definition to prolog indent width Defaults to t prolog keywords This is a list with keywords that are highlighted in a special color when used as com mands i e as keyword Defaults to sicstus block dynamic mode module multifile meta predicate parallel public sequential volatile prolog electric newline flag Set to nil to prevent Emacs from automatically indenting the next line when pressing RET Defaults to t prolog hungry delete key flag Set to t to enable deletion of all white space before the cursor when pressing the delete key unless inside a comment string or quoted atom Defaults to nil prolog electric dot flag Set to t to enable the electric dot function If enabled pressing at the end of a non empty line inserts a dot and a newline When pressed at the beginning of a line a new head of the last predicate is inserted When pressed at the end of a line with only whitespace a recursive call to the current predicate is inserted The function respects the arity of the predicate and inserts parentheses and the correct number of commas for separation of the arguments Defaults to nil prolog electric underscore flag Set to t to enable
367. l SP_initialize before calling any other interface function The function will allocate data areas used by Prolog initialize command line arguments so that they can be accessed by the argv Prolog flag and load the Runtime Library int SP_initialize int argc char argv char boot_path boot_path should be the name of a directory equivalent to SP_PATH bin If boot_path is NULL SP initialize will look up the value of the environment variable SP PATH and look for the file SP_PATH bin sprt sav which contains the Runtime Library It returns SP SUCCESS if initialization was successful and SP ERROR otherwise Optionally you may also call SP force interactive before calling SP initialize This will force the I O built in predicates to treat the standard input stream as a terminal even if it does not appear to be a terminal Same as the i option in Development Systems see Section 1 1 Start page 7 152 SICStus Prolog void SP force interactive void Optionally you may also call SP set memalloc hooks before calling SP_initialize This will define the bottom layer of Prolog s memory manager in case your application has special requirements typedef void SP AllocHook unsigned int size unsigned int align unsigned int actual_sizep typedef void SP_ReAllocHook void ptr unsigned int oldsize unsigned int newsize unsigned int align unsigned int actual_sizep typedef int SP_Free
368. lation Ordinary disjunction P Q is treated by the compiler as an anonymous predicate with two clauses and the execution of a disjunction relies on backtracking to explore the two disjuncts If then else statements of the form f gt Then Else are recognized by the compiler and are under certain conditions compiled to code that is much more efficient than the corresponding disjunction essentially turning the If test to a conditional jump and often avoiding costly backtracking altogether Chapter 10 Programming Tips and Examples 179 For this optimization to be effective the test must be a conjunction of a restricted set of built in predicates roughly arithmetic tests type tests and term comparisons This optimization is actually somewhat more general than what is described above A sequence of guarded clauses Headl Guardl Bodyl Headm Guardm Bodym Headn Bodym is eligible for the same optimization provided that the arguments of the clause heads are all unique variables and that the guards are simple tests as described above 10 5 Programming Examples The rest of this chapter contains a number of simple examples of Prolog programming illustrating some of the techniques described above 10 5 1 Simple List Processing The goal concatenate L1 L2 L3 is true if list L3 consists of the elements of list L1 concatenated with the elements of list L2 The goal member X L is true if X is one of the
369. lauses can be added asserted or removed from the program retracted For these predicates the argument Head must be instantiated to an atom or a compound term with an optional module prefix The argument Clause must be instantiated either to a term Head Body or if the body part is empty to Head with an optional module prefix An empty body part is represented as true 114 SICStus Prolog Note that a term Head Body must be enclosed in parentheses when it occurs as an argument of a compound term as is a standard infix operator with precedence greater than 1000 see Section 2 6 Operators page 37 e g assert Head Body Like recorded terms see Section 7 10 Database page 115 the clauses of dynamic predicates have a unique implementation defined identifier Some of the predicates below have an additional argument which is this identifier This identifier makes it possible to access clauses directly instead of requiring a normal database hash table lookup assert Clause assert Clause Ref The current instance of Clause is interpreted as a clause and is added to the current interpreted program The predicate concerned must currently be dynamic or undefined and the position of the new clause within it is implementation defined Ref is a unique identifier of the asserted clause Any uninstantiated variables in the Clause will be replaced by new private variables along with copies of any subgoals bl
370. lem certain atoms will be relocated during restore as follows e Atoms that had SP_PATH library the name of the directory containing the Prolog Library as prefix at save time will have that prefix replaced by the corresponding restore time value e Atoms that had the name of the directory containing File as prefix at save time will have that prefix replaced by the corresponding restore time value 18 SICStus Prolog The purpose of this procedure is to be able to build and deploy an application consisting of a saved state and other files as a directory tree with the saved state at the root as long as the other files maintain their relative position in the deployed copy they can still be found upon restore Note Foreign resources see Section 8 2 Calling C page 128 are unloaded by save_ program 1 2 The names and paths of the resources typically SP_PATH library relative are however included in the saved state After the save and after restoring a saved state this information is used to reload the foreign resources again The state of the foreign resource in terms of global C variables and allocated memory is thus not preserved Foreign resources may define init and deinit functions to take special action upon loading and unloading see Section 8 2 6 Init and Deinit Functions page 134 In the Muse Development System the above predicates may only be called when the system has been adjusted to one worker see Section 3
371. line and removes module prefixes that are redundant wrt the current type in module Options is a list of zero or more of the following where Boolean must be true or false false is the default quoted Boolean If selected functors are quoted where necessary to make the result accept able as input to read 1 write_canonical 1 writeq 1 and portray clause 1 select this ignore ops Boolean If selected Term is written in standard parenthesized notation instead of using operators write_canonical 1 and display 1 select this portrayed Boolean If selected user portray 1 is called for each subterm print 1 selects this numbervars Boolean If selected occurrences of VAR N where N is an integer gt 0 are treated specially see numbervars 3 print 1 write 1 writeq 1 and portray clause 1 select this cycles Boolean If selected the potentially cyclic term is printed in finite 9 2 notation as discussed above indented 4Boolean If selected the term is printed with the same indentation as is used by portray clause 1 and listing 0 1 max depth N Depth limit on printing N is an integer 0 the default means no limit format Format Arguments format Stream Format Arguments Prints Arguments onto Stream according to format Format Format is a list of for matting characters If Format is an atom then name 2 see Section 7 7 Meta Logic page 110 will be used to translate it into a list
372. list of streams in Streams is checked for readable characters A stream can be any stream associated with an I O descriptor The list ReadStreams returns the streams with readable data socket_select 5 also waits for connections to the sockets specified by TermsSock ets This argument should be a list of Term Socket pairs where Term which can be any term is used as an identifier NewTermsStreams is a list of Term connection Client Stream pairs where Stream is a new stream open for commu nicating with a process connecting to the socket identified with Term Client is the client host address see socket_accept 3 If TimeOut is instantiated to off the predicate waits until something is available If TimeOut is S U the predicate waits at most S seconds and U microseconds Both S and U must be integers gt 0 If there is a timeout ReadStreams and NewTermsStreams are O Socket select Sockets NewStreams TimeOut Streams ReadStreams socket select Socket NewStream TimeOut Streams ReadStreams socket_select Sockets NewStreams NewClients TimeOut Streams ReadStreams socket_select Socket NewStream NewClient TimeOut Streams ReadStreams These forms which are provided for backward compatibility only differs in how sockets are specified and new streams returned socket_select 5 6 also wait for connections to the sockets in the list Sockets NewStreams is the list of new streams opened for communica
373. lligence 13 231 278 1980 Regin 94 J C Regin A filtering algorithm for constraints of difference in CSPs Proc of the Twelfth National Conference on Artificial Intelligence AA AI 94 pp 362 367 1994 Robinson 65 J A Robinson A Machine Oriented Logic Based on the Resolution Principle Journal of the ACM 12 23 44 January 1965 408 SICStus Prolog Roussel 75 P Roussel Prolog Manuel de Reference et d Utilisation Groupe d Intelligence Arti ficielle Marseille Luminy 1975 Saraswat 90 V Saraswat Concurrent Constraint Programming Languages PhD thesis Carnegie Mellon University 1990 Sterling amp Shapiro 86 L Sterling and E Shapiro The Art of Prolog The MIT Press Cambridge MA 1986 Van Hentenryck 89 P Van Hentenryck Constraint Satisfaction in Logic Programming Logic Programming Series The MIT Press 1989 Van Hentenryck et al 92 P Van Hentenryck V Saraswat and Y Deville Constraint processing in cc FD unpublished manuscript 1992 Van Hentenryck amp Deville 91 P Van Hentenryck and Y Deville The Cardinality Operator a new logical connective and its application to constraint logic programming In Eighth International Confer ence on Logic Programming 1991 Van Hentenryck et al 95 P Van Hentenryck V Saraswat and Y Deville Design implementation and evaluation of the constraint language cc FD In A Podelski ed Constraints Basics and Trends volume 910 of Lec
374. log at_end_of_line at_end_of_line Stream fileerrors The end of stream or end of line has been reached for Stream An input stream reaches end of line when all the characters except LFD of the current line have been read These predicates peek ahead for next input character if there is no character available on the buffer of Stream Undoes the effect of nofileerrors 0 nofileerrors After a call to this predicate failure to locate or open a file will cause the operation to fail instead of the default action which is to raise an exception with an error message stream select Streams TimeOut ReadStreams The list of streams in Streams is checked for readable characters A stream can be any stream associated with an I O descriptor The list ReadStreams returns the streams with readable data If TimeOut is instantiated to off the predicate waits until some thing is available If TimeOut is S U the predicate waits at most S seconds and U microseconds Both S and U must be integers gt 0 If there is a timeout ReadStreams is Not available in Muse Not available in operating systems that do not support the system system call Stream interrupt Stream OldHandler NewHandler Installs NewHandler as an interrupt handler which is invoked when something is read able on Stream OldHandler is the current interrupt handler Stream must be associated with an I O descriptor Interrupt handlers are specified as atoms The atom
375. log flag FlagName Value Value is the current value of the Prolog flag FlagName Can be used to enumerate all Prolog flags and their values by backtracking prolog load context Key Value This predicate gives access to context variables during compilation and loading of Prolog files It unifies Value with the value of the variable identified by Key Possible keys are file The absolute path name of the file being compiled During loading of a ql file the corresponding source file name is returned directory The absolute path name of the directory of the file being compiled loaded module The source module see Section 4 5 Meta Exp page 49 This is useful for example if you are defining clauses for user term_expansion 2 4 and need to access the source module at compile time Stream The stream being compiled or loaded from term_position A term representing the position of the last clause read see Section 7 1 5 Stream Pred page 89 statistics Displays on the standard error stream statistics relating to memory usage run time garbage collection of the global stack and stack shifts statistics Key Value This allows a program to gather various execution statistics For each of the possible keys Key Value is unified with a list of values as follows global_stack size used free This refers to the global stack where compound terms are stored The values are gathered before the list holding the answers i
376. log flag names and values are agc margin An integer Margin The atoms will be garbage collected when Margin new atoms have been created since the last atom garbage collection Initially 10000 argv A read only flag The value is a list of atoms of the program arguments sup plied when the current SICStus Prolog process was started For example if SICStus Prolog were invoked with sicstus a hello world 2001 then the value will be hello world 2001 compiling Governs the mode in which compile 1 and fcompile 1 operate see Chap ter 5 Load Intro page 51 compactcode Compilation produces byte coded abstract instructions the default fastcode Compilation produces native machine instructions Currently only available for 680x0 Sparc and MIPS platforms profiledcode Compilation produces byte coded abstract instructions instru mented to produce execution profiling data debugcode Compiling is replaced by consulting debugging Corresponds to the predicates debug 0 nodebug 0 trace 0 notrace 0 zip 0 nozip O0 see Section 7 14 Debug Pred page 120 trace Turns on trace mode debug Turns on the debugger 106 character_ fileerrors ge gc_margin gc_trace SICStus Prolog off Turns off trace mode and the debugger the default This flag is not available in Runtime Systems escapes on or off If this flag is on a backslash occurring inside integers in 0 notation or inside quoted at
377. log use prolog tokenizer flag to nil This means that Emacs uses built in functions for some of the source code parsing thus speeding up indentation The problem is that it does not handle all peculiarities of the Prolog syntax so this is a trade off between correctness and speed e The setting of the prolog parse mode variable also affects the speed beg of line being faster than beg of clause 1 11 6 4 Changing Colors The prolog mode uses the default Emacs colors for font locking as far as possible The only custom settings are in the prolog process buffer The default settings of the colors may not agree with your preferences so here is how to change them First of all list all available faces a face is a combined setting of foreground and background colors font boldness etc by typing M x list faces display There are several functions that change the appearance of a face the ones you will most likely need are set face foreground set face background set face underline p make face bold make face bold italic make face italic make face unbold make face unitalic These can be tested interactively by typing M x function name You will then be asked for the name of the face to change and a value If the buffers are not updated according to the new settings then refontify the buffer using the Fontify Buffer menu entry in the Prolog menu Colors are specified by a name or by RGB values Available color names can be listed wi
378. lpha string item gt char other than or V uu escape sequence gt layout text item gt layout char comment char where char must not contain 4 char LFD where char must not contain LFD the following token if any must be layout text any character i e layout char alpha symbol char solo char punctuation char quote char Full Prolog Syntax 401 alpha capital letter small letter digit underline escape sequence gt b backspace character code 8 horizontal tab character code 9 newline character code 10 vertical tab character code 11 1 form feed character code 12 1 carriage return character code 13 1 escape character code 27 Y delete character code 127 1 alarm character code 7 alpha alpha treating a b and A B as 10 11 in the range 0 15 hex character code 3 digit digit digit 1 in the range 0 7 octal character code 1 delete character code 127 capital letter small letter 1 the control character alpha mod 32 c layout char ignored layout char ignored char other than the above represents itself 47 QaOoK hd Bat Escape Sequences A backslash occurring inside integers in 0 notation or inside quoted atoms or strings has special meaning and indicates the start of an escape sequence C
379. lvers including 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 straightfor ward 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 programs on the fly and a runtime system 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 con straints into simpler ones until they are solved CHR define both simplification of and propagation 306 SICStus Prolog over constraints Simplification replaces constraints by simpler constraints while preserving log ical equivalence e g X gt Y Y gt X lt gt fail Propagation adds new constraints which are logically redundant but may cause further simplification e g X gt Y Y gt Z
380. ly heavy weight To be able to create efficiently light weight objects we intro duce the notion of instances An instance is an object with restricted capability It is created from an object that is considered its class It gets a copy of the attributes of its class These can be modified by get 1 and set 1 An instance cannot be a class for other instances Instances are in general very efficient both in space and access modification time The attribute class 1 will store the identity of the class of the instance including parameters 32 8 Built In Objects and Methods 32 8 1 Universal Methods The following methods are universal i e they are defined locally if appropriate for every object super Object NotInherit List Object is a parent a super object of Self NotInheritList specifies methods of Ob ject explicitly not inherited by Self The definition super Object is translated to super Object 1 attributes Attributes Attributes is a list of compound terms specifying the local attributes of Self and the initial values 32 8 2 Inlined Methods The following methods are compiled inline i e calls are replaced by definitions This implies in the current implementation that they have a fixed semantics an can not be redefined There are also definitions for these methods in object covering the cases of unexpanded calls self Self Unifies Self with self get Attribute Gets the attribute value
381. m Da Goals O ord intersect O0ther Da verify_attributes _ _ attribute_goal Var domain Var Dom get_atts Var dom Dom domain X Dom var Dom get_atts X dom Dom domain X List list_to_ord_set List Set Set El Els Els gt 4 X El E put atts Fresh dom Set X Fresh SICStus Prolog 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 may call verify attributes 3 Note that the implied binding Other El was deferred until after the completion of verify attribute 3 Otherwise there might be a danger of recursively invoke verify attribute 3 which might bind Var which is not allowed inside the scope of verify attribute 3 Defer ring unifications into the third argument of verify attribute 3 effectively serializes th calls to verify attribute 3 Assuming that the code resides in the file domain p1 we can use it via use module domain Let s test 1t Chapter 14 Attributed Variables 197 domain X 5 6 7 1 domain Y 3 4 5 6 domain Z 1 6 7 8 domain X 1 5 6 7 domain Y 3 4 5 6 domain Z 1 6 7 8 yes dom
382. m as the fields of a record Compound terms are usefully pictured as trees For example the term s np john vp v likes np mary would be pictured as the structure S PON np Xp iN john v np likes mary Sometimes it is convenient to write certain functors as operators 2 ary functors may be declared as infix operators and 1 ary functors as prefix or postfix operators Thus it is possible to write e g X Y P Q X lt Y X P as optional alternatives to X Y PQ Q Y X P The use of operators is described fully below see Section 2 6 Operators page 37 Lists form an important class of data structures in Prolog They are essentially the same as the lists of LISP a list either is the atom representing the empty list or is a compound term with functor and two arguments which are respectively the head and tail of the list Thus a list of the first three natural numbers is the structure IN 1 3 IN 2 ZN 3 0 which could be written using the standard syntax as 1 2 3 but which is normally written in a special list notation as 30 SICStus Prolog 1 2 3 The special list notation in the case when the tail of a list is a variable is exemplified by XIL a b L representing PR X L a EN b L respectively Note that this notation does not add any new power to the language it simply makes it more readable e g the above examples could equally be written X L
383. matically imported into each new module as it is created 48 SICStus Prolog 4 2 Module Prefixing Notwithstanding the visibility rules any predicate can be called from any other module by prefixing the goal with the module name and the colon operator thus overriding the source module of the goal foo bar X This feature is intended mainly for debugging purposes since it defies the purposes of the module system If the prefixed goal is a meta predicate however the prefixed module name may affect the module name expansion of the goal see Section 4 5 Meta Exp page 49 It is also possible to override the source module of clauses and directives by module prefixing For example dynamic mod p 1 p X mod q X r X mod q X r X mod s X t X declares mod p 1 as dynamic whatever the source module is defines p 1 in the source module as calling mod q 1 and mod r 1 defines mod q 1 as calling mod r 1 and defines mod s 1 as calling t 1 in the source module The latter technique is particularly useful when the prefix is user and the predicate is a hook predicate such as user portray 1 which must be defined in the user module but the rest of the file consists of predicates belonging to some other module 4 3 Defining Modules A module is normally defined by putting a module declaration first in a source file A module declaration has the form module ModuleName ExportList Options When
384. may be written as any sequence of alphanumeric characters including _ starting with either a capital letter or _ e g X Value A Al 3 _RESULT If a variable is only referred to once in a clause it does not need to be named and may be written as an anonymous variable indicated by the underline character _ A clause may contain several anonymous variables they are all read and treated as distinct variables A variable should be thought of as standing for some definite but unidentified object This is analogous to the use of a pronoun in natural language Note that a variable is not simply a writable storage location as in most programming languages rather it is a local name for some data object cf the variable of pure LISP and identity declarations in Algol68 2 1 1 5 Compound Terms The structured data objects of the language are the compound terms A compound term comprises a functor called the principal functor of the term and a sequence of one or more terms called arguments A functor is characterized by its name which is an atom and its arity or number of arguments For example the compound term whose functor is named point of arity 3 with arguments X Y and Z is written Chapter 2 The Prolog Language 29 point X Y Z Note that an atom is considered to be a functor of arity 0 Functors are generally analogous to common nouns in natural language One may think of a functor as arecord type and the arguments of a compound ter
385. mber of applications Note that the predicates in the Prolog library are not built in predicates One has to explicitly load each package to get access to its predicates The following packages are provided arrays provides an implementation of extendible arrays with logarithmic access time assoc uses AVL trees to implement association lists i e extendible finite mappings from terms to terms atts provides a means of associating with variables arbitrary attributes i e named proper ties that can be used as storage locations as well as hooks into Prolog s unification heaps implements binary heaps the main application of which are priority queues lists provides basic operations on lists terms provides a number of operations on terms ordsets defines operations on sets represented as lists with the elements ordered in Prolog standard order queues defines operations on queues FIFO stores of information random provides a random number generator system provides access to operating system services trees uses binary trees to represent non extendible arrays with logarithmic access time The functionality is very similar to that of library arrays but library trees is slightly more efficient if the array does not need to be extendible ugraphs provides an implementation of directed and undirected graphs with unlabeled edges wgraphs provides an implementation of directed and undirected graphs where each edge has an integral we
386. mbitious users who need control over branching or who want to add cutting planes for example Anyway here is a small problem from miplib a collection of MIP models housed at Rice University NAME flugpl ROWS 18 COLUMNS 18 INTEGER 11 NONZERO 46 BEST SOLN 1201500 opt LP SOLN 1167185 73 SOURCE Harvey M Wagner John W Gregory Cray Research E Andrew Boyd Rice University APPLICATION airline model COMMENTS no integer variables are binary from file library Cclpqr examples mip example flugpl Obj Vs Ints Vs Anmi Anm2 Anm3 Anm4 Anmb5 Anm6 Stm1 Stm2 Stm3 Stm4 Stm5 Stm6 UE1 UE2 UE3 UE4 UE5 UE6 Stm6 Stm5 Stm4 Stm3 Stm2 Anm6 Anm5 Anm4 Anm3 Anm2 Anmi Ints 2700 Stmi 2700 Stm2 2700 Stm3 2700 Stm4 2700 Stm5 2700 Stm6 1500 Anm1 1500 Anm2 1500 Anm3 1500 Anm4 1500 Anm5 1500 Anm6 30 UE1 30 UE2 30 UE3 30 UE4 30 UE5 30 UE6 0bj allpos Vs Stmi 60 0 9 Stm1 1 Anm1 1 Stm2 0 0 9 Stm2 1x Anm2 1 Stm3 0 0 9 Stm3 1 Anm3 1 Stm4 0 9 Stm4 1x Anm4 1 Stm5 0 0 9 Stm5 1i Anm5 1 Stm6 150 Stm1 150 Stm2 150 Stm3 150 Stm4 150 Stm5 150 Stm6 100 Anmi 100 Anm2 100 Anm3 100 Anm4 100 Anm5 100 Anm6 1x UE1 gt 1 UE2 1x UE3 gt 1x UE4 1x UE5 gt 1 UE6 gt 8000 9000 8000 10000 9000 12000 Chapter 29 Constraint Logic Programming over Ratio
387. ment will be passed to write 1 see Section 7 1 3 Term I O page 80 Example format Hello w world A B Hello A B world Call The argument is a goal which will be called and expected to print on the current output stream If the goal is not a built in predicate it should be module prefixed as format 2 3 are not meta predicates If the goal performs other side effects or does not succeed deterministically the behavior is undefined Example format Hello world write new Hello new world Print tilde Takes no argument Prints Example format Hello world Hello world Print newline Takes no argument Prints N newlines N defaults to 1 Example format Hello n world Hello world Print Newline Prints a newline if not at the beginning of a line The following control sequences set column boundaries and specify padding A column is defined as the available space between two consecutive column boundaries on the same line A boundary is initially assumed at line position 0 The specifications only apply to the line currently being written When a column boundary is set or and there are fewer characters written in the column than its specified width the remaining space is divided equally amongst the pad sequences t in the column If there are no pad sequences the column is space padded at the end Chapter
388. mple descendants sess 179 10 5 8 Association List Primitives oooooooomoo 180 10 5 4 Differentiation 00 Ie 181 10 5 5 Use of Meta Logical Predicates o oo o 181 10 5 6 Use of Term Expansion e esee 182 10 5 7 Prolog in Prolog oer tn iaa as 182 10 5 8 Translating English Sentences into Logic Formulae 183 10 5 9 Muse FLI Example esee BRA 184 11 The Prolog Library e esses 187 12 Array Operations 24 ean IA EX a 189 13 Association Lists o 2io ei4250 5 eee tees ee 191 14 Attributed Variables 0004 193 15 Heap Operations cece eee ee 199 16 List Operations icin cte e de aris ee enr y dees da 201 T7 Term Utilities i eer ef etu bMS 205 18 Ordered Set Operations 207 19 Queue Operations 00 eee eee 211 20 Random Number Generator 213 21 Operating System Utilities 215 22 Updatable Binary Trees 219 23 Unweighted Graph Operations 221 24 Weighted Graph Operations 225 25 Sockel 1 De coo sete gate cs oye cays EU QUA RN 229 vi SICStus Prolog 26 Linda Process Communication 231 20 1 Setveri olei a RDREL PR WERE ela eddy aie ERI 232 20 2 Cloacas 233 27 External Storage of Terms External Database Vets paid iac ite eth paa ad ee
389. n 724 solutions in 10 400 seconds yes Speedup is 10400 2760 Speedup 3 7681159420289854 yes halt Chapter 3 Running Prolog in Parallel 43 3 3 Main Issues of Parallel Execution 3 3 1 The Muse Model The Muse model assumes a multiprocessor system with a number of processors or processes called workers with identical local address spaces and some global address space shared by all workers We use the term worker to represent a process or processor The Muse model implements each worker as a sequential Prolog engine with its own WAM stacks in private memory The Prolog program is stored in shared memory During execution the actual work is to explore a search tree implicitly defined by the Prolog program The available work is represented as choicepoints containing outstanding execution al ternatives on one of the WAM stacks The work is performed concurrently by the workers A distributed scheduler is responsible for dynamic load balancing of available work among available workers Workers try to maximize the time they spend working and minimize the time they spend scheduling When a worker is working it adopts a depth first left to right search strategy In the Muse model each worker keeps its own WAM stacks to avoid conflicting variable bindings in common parts of the search tree Whenever a worker runs Prolog it therefore can use more or less the same machinery as the sequential SICStus Prolog impleme
390. n Stream Position ISO Position is a term representing a new position of Stream which is then set to the new position This operation is only available for Prolog streams connected to seekable devices disk files usually seek Stream Offset Method NewLocation True if the stream Stream can be set to the byte offset Offset relative to Method and NewLocation is the new byte offset from the beginning of the file after the operation Method must be one of bof Seek from the beginning of the file stream current Seek from the current position of the file stream eof Seek from the end of the file stream This operation is only available for Prolog streams connected to seekable devices disk files usually and is an interface to the stdio functions fseek and ftell at end of stream ISO at end of stream Stream ISO The end of stream has been reached for Stream An input stream reaches end of stream when all characters except EOF of the stream have been read These predicates peek ahead for next input character if there is no character available on the buffer of Stream Unless the stream is to be treated as connected to the terminal see SP_ force interactive Section 8 8 1 Initializing the Prolog Engine page 151 a stream remains at end of stream after EOF has been read and any further attempt to read from the stream will raise an existence error see Section 7 5 Exception page 101 92 SICStus Pro
391. n an expandable position in the head of the clause Some examples user meta predicate p q r X p X a x p X D user consulted 40 msec 1088 bytes yes 50 SICStus Prolog listing r A p user A q A p A yes Here p 1 and q 1 are declared as meta predicates while r 1 is not Thus the clause r X p X will be transformed to r X p M X by item 2 above where M is the type in module whereas q X p X will not m assert f 1 Here assert 1 is called in the module m However this does not ensure that f 1 is asserted into m The fact that assert 1 is a meta predicate makes the system module name expand the goal transforming it to m assert m f 1 before execution This way assert 1 is supplied the correct module information 4 6 Meta Predicate Declarations The fact that a predicate needs module name expansion is declared in a meta predicate declaration meta predicate MetaPredSpec MetaPredSpec where each MetaPredSpec is a mode spec E g meta predicate p which means that the first argument of p 2 shall be module name expanded The arguments in the mode spec are interpreted as An integer This argument in any call to the declared predicate shall be expanded Integers are allowed for compatibility reasons Anything else e g or This argument shall not be expanded A number of built in predicates have pre
392. n certain programming constructs such as failure driven loops e g the loop program initialize generate solution X process solution X fail if not last X l t shut down will generate an unbounded number of suspended branches if generate solution 1 is a parallel predicate with an unbounded number of alternatives and process solution 1 involves a synchro nized operation In some rare cases it might also be useful to prevent slow down due to too fine granularity in some predicate call To find such cases you may use the Must trace tool see Section 3 4 1 Must page 45 58 SICStus Prolog 5 3 Considerations for File To File Compilation When compiling a source file to an object file remember that clauses are loaded and directives are executed at run time not at compile time Only predicate declarations are processed at compile time For instance it does not work to include operator declarations or clauses of user term_ expansion 2 4 or user goal expansion 3 or any auxiliary predicates that they might need and rely on the new transformations to be effective for subsequent clauses of the same file or subsequent files of the same compilation Any directives or clauses that affect the compile time environment must be loaded prior to compiling source files to object files This also holds for meta predicates called by the source files but defined elsewhere for module name expansion to work correctly If this s
393. n of all the sets in Sets fdset_member Elt Set is true when Elt is a member of Set If Elt is unbound Set must be finite fdset_eq Set1 Set2 Is true when the two arguments represent the same set i e they are identical fdset_subset Set1 Set2 Every element of Set appears in Set2 fdset_subtract Set1 Set2 Difference Difference contains all and only the elements of Set1 which are not also in Set2 fdset_union Set1 Set2 Union Union is the union of Set1 and Set2 fdset_union Sets Union Union is the union of all the sets in Sets fdset_complement Set Complement Complement is the complement of Set wrt inf sup 30 8 4 A Global Constraint Example The following example defines a new global constraint exactly X L N which is true if X occurs exactly N times in the list L of integers and domain variables A version defined in terms of reified equalities was presented earlier see Section 30 2 3 Reified Constraints page 274 This example illustrates the use of state information The state has two components the list of variables that could still be X and the number of variables still required to be X The constraint is defined to wake up on any domain change Chapter 30 Constraint Logic Programming over Finite Domains 289 An implementation of exactly I X 1 X m N Necessary condition 0 lt N lt m Rewrite rules 1 X i I gt exactly I X 1 X i 1 X i 1
394. n of directives is produced and variable bindings are not displayed Directives that fail or raise exceptions cause warnings but do not terminate the load Most of the predicates listed below take an argument Files which is a single file name or a list of file names Source files usually end with an p1 suffix and object file names with an ql suffix These suffixes are optional Each file name may optionally be prefixed by a module name The module name specifies where to import the exported predicates of a module file or where to store the predicates of a non module file The module is created if it doesn t exist already absolute_file_name 2 see Section 7 1 5 Stream Pred page 89 is used to look up the files The file name user is reserved and denotes the standard input stream These predicates are available in Runtime Systems with the following limitations e The compiler is not available so compiling is replaced by consulting e The redefine_warnings and single_var_warnings Prolog flags have no effect e Progress and warning messages are not issued e The user is not prompted in the event of name clashes etc load files Files load files Files Options A generic predicate for loading files with a list of options to provide extra control This predicate in fact subsumes the other predicates except use module 3 which also returns the name of the loaded module Options is a list of zero or more of the following 7
395. n that this layer of memory management wants to do realloc_hook is called with a piece of memory to be resized and possibly moved ptr is the pointer oldsize its current size The function must allocate and return a pointer to a piece of memory that has at least newsize bytes aligned at align in it and that has the same contents as the old block up to the lesser of oldsize and newsize align is guaranteed to be a power of 2 The actual size of the piece of memory should be returned in actual sizep Should return NULL if it cannot allocate any more memory or if it cannot reclaim the old block in a meaningful way In that case Prolog will use the other functions free hook is called with a pointer to the piece of memory to be freed and its size Should return non zero iff the function was able to free this piece of memory Otherwise Prolog will keep using the memory as if it were not freed The default bottom layers look at the environment variables PROLOGINITSIZE PROLOGINCSIZE PROLOGKEEPSIZE and PROLOGMAXSIZE They are useful to customize the default memory manager If users redefine the bottom layer they can choose to ignore these environment variables See Section 1 1 2 Environment Variables page 10 8 8 2 Loading Prolog Code You can load your Prolog code compiled to Prolog object files into the system with the call SP_ load This is the C equivalent of the Prolog predicate load 1 int SP load char filename Alternativel
396. n their effect as possible If a predicate is intended to be deterministic define it as such do not rely on its callers to prevent unintended backtracking e Binding output arguments before a cut is a common source of programming errors so don t do it e Replace cuts by if then else constructs if the test is simple enough see Section 10 4 IfThen Else page 178 e Use disjunctions sparingly always put parentheses around them never put parentheses around the individual disjuncts never put the at the end of a line e Write the clauses of a predicate so that they discriminate on the principal functor of the first argument see below For maximum efficiency avoid defaulty programming catch all clauses e Don t use lists round lists or braces to represent compound terms or tuples of some fixed arity The name of a compound term comes for free 178 SICStus Prolog 10 2 Indexing The clauses of any predicate are indexed according to the principal functor of the first argument in the head of the clause This means that the subset of clauses which match a given goal as far as the first step of unification is concerned is found very quickly in practically constant time This can be very important where there is a large number of clauses for a predicate Indexing also improves the Prolog system s ability to detect determinacy important for conserving working storage and stron
397. n_resource ex f1 f2 load_foreign_resource ex and a C source file ex c with definitions of the functions f1 and 2 both returning long and having a long as only parameter The conversion declarations in ex p1 state that these functions form the foreign resource ex To create the linked foreign resource simply type to Prolog link_foreign_resource ex ex p1 dynamic ex c 1 01 1 or alternatively to the Shell splfr ex ex pl tc ex c The linked foreign resource ex so file suffix so is system dependent has been created It will be dynamically linked by the directive load_foreign_resource ex when the file ex pl is loaded Linked foreign resources can also be created manually see Chapter 38 Runtime Utilities page 373 Dynamic linking of foreign resources can also be used by Runtime Systems On some platforms however the executable must not be stripped for dynamic linking to work i e its symbol table must remain 8 3 Support Functions The support functions include functions to manipulate SP_term_refs functions to convert data between the basic C types and Prolog terms functions to test whether a term can be converted to a specific C type and functions to unify or compare two terms 136 SICStus Prolog 8 3 1 Creating and Manipulating SP_term_refs Normally C functions only have indirect access to Prolog terms via SP_term_refs C functions may receive arguments as
398. nals or Reals 269 20x Stm1 1 UE1 lt 0 20 Stm2 1 UE2 lt 0 20 Stm3 1 UE3 20 Stm4 1 UE4 lt 0 20 Stm5 1 UE5 lt 0 20 Stm6 1 UE6 Anmi lt 18 57 lt Stm2 Stm2 lt 75 Anm2 lt 18 57 lt Stm3 Stm3 lt 75 Anm3 lt 18 57 lt Stm4 Stm4 lt 75 Anm4 lt 18 57 lt Stm5 Stm5 lt 75 Anm5 lt 18 57 lt Stm6 Stm6 lt 75 Anm6 lt 18 ll oo ll allpos allpos X Xs X gt 0 allpos Xs We can first check whether the relaxed problem has indeed the quoted infimum clp r example flugpl Obj _ _ _ inf 0bj Inf Inf 1167185 7255923203 Computing the infimum under the additional constraints that Stm6 Stm5 Stm4 Stm3 Stm2 Anm6 Anm5 Anm4 Anm3 Anm2 Anm1 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 Vertex 0 001 Inf 1201500 0000000005 Vertex 75 0 70 0 70 0 60 0 60 0 0 0 12 0 7 0 16 0 6 0 6 0 29 9 Implementation Architecture The system consists roughly of the following components e A polynomial normal form expression simplification mechanism e A solver for linear equations Holzbaur 92 e A simplex algorithm to decide linear inequalities Holzbaur 94 29 9 1 Fragments and Bits 29 9 1 1 Rationals The internal data structure for rational numbers is rat Num Den Den is always positive i e the s
399. nced 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 32 Prolog Objects 327 32 Prolog Objects Prolog Objects is an extension to SICStus Prolog for flexible structuring sharing and reuse of knowledge in large logic programming applications Prolog Objects enhances Prolog with an ex pressive and efficient object oriented programming component Prolog Objects is based on the notion of prototypes In object oriented programming a prototype is an object that represents a typical behavior of a certain concept A prototype can be used as is or as a model to construct other objects that share some of the characteristics of the prototypical object These specialized objects can themselves become prototypes used to construct other objects and so forth The basic mechanism for sharing is by inheritance and delegation Inheritance is known for most readers By using the delegation mechanism an object can forward a message to another object to invoke a method defined by the recipient but interpreted in the context of the sender In Prolog Objects an object is a named collection of predicate definitions In this sense an object is similar to a Prolog module The object system can be seen as an extension of SICStus Prolog s module system In addition an object may have attributes that are modifiable Predicate definitions belonging to an object ar
400. nces of tokens Tokens are sequences of characters which are treated as separate symbols Tokens include the symbols for variables constants and functors as well as punctuation characters such as brackets and commas We define below how lists of tokens are interpreted as terms see Term Token page 397 Each list of tokens which is read in for interpretation as a term or sentence has to be terminated by a full stop token Two tokens must be separated by a layout text token if they could otherwise be interpreted as a single token Layout text tokens are ignored when interpreting the token list as a term and may appear at any point in the token list We define below defines how tokens are represented as strings of characters see Token String page 398 But we start by describing the notation used in the formal definition of Prolog syntax see Syntax Notation page 395 Notation 1 Syntactic categories or non terminals are written thus item Depending on the section a category may represent a class of either terms token lists or character strings 2 A syntactic rule takes the general form C gt Fl F2 F3 which states that an entity of category C may take any of the alternative forms F1 F2 F3 etc 3 Certain definitions and restrictions are given in ordinary English enclosed in brackets 4 A category written as C denotes a sequence of one or more Cs 5 A category written as C denotes an optional C Therefo
401. nction containing a cut A proper use of the cut is usually a major difficulty for new Prolog programmers The usual mistakes are to over use cut and to let cuts destroy the logic A cut that doesn t destroy the logic is called a green cut a cut that does is called a red cut We would like to advise all users to follow these general rules Also see Chapter 10 Example Intro page 177 e Write each clause as a self contained logic rule which just defines the truth of goals which match its head Then add cuts to remove any fruitless alternative computation paths that may tie up memory e Cuts are usually placed right after the head sometimes preceded by simple tests e Cuts are hardly ever needed in the last clause of a predicate 2 6 Operators Operators in Prolog are simply a notational convenience For example the expression 2 1 could also be written 2 1 This expression represents the data structure and not the number 3 The addition would only be performed if the structure were passed as an argument to an appropriate predicate such as is 2 see Section 7 2 Arithmetic page 94 The Prolog syntax caters for operators of three main kinds infix prefix and postfix An infix operator appears between its two arguments while a prefix operator precedes its single argument and a postfix operator is written after its single argument Each operator has a precedence which is a number from 1 to 1200 The precedence is used to disambig
402. nd Value is its value Both are atoms Can be used to enumerate all current environment variables exec Command Stdin Stdout Stderr Pid Passes Command to a new default shell process for execution The standard I O streams of the new process are connected according to what is specified by the terms Stdin Stdout and Stderr respectively Possible values are null Connected to dev null or equivalent std The standard stream is shared with the calling process Note that the standard stream may not be referring to a console if the calling process is windowed To portably print the output from the subprocess on the Prolog console pipe 1 must be used and the program must explicitly read the pipe and write to the console Similarly for the input to the subprocess 216 SICStus Prolog pipe Stream A pipe is created which connects the Prolog stream Stream to the standard stream of the new process It must be closed using close 1 it is not closed automatically when the process dies Pid is the process identifier of the new process On UNIX the subprocess will be detached provided none of its standard streams is specified as std This means it will not receive an interruption signal as a result of C being typed file exists FileName FileName is the name of an existing file or directory file exists FileName Permissions FileName is the name of an existing file or directory which can be accessed according to
403. nd then follow the control flow through these by leaping from one to the other Debugging information is collected while leaping so when a spy points is reached it is possible to inspect the ancestor goals or creep into them upon entry to Redo ports zip is like leap except no debugging information is being collected while zipping re sulting in significant savings in memory and execution time 66 SICStus Prolog skip is only valid for Call and Redo ports It skips over the entire execution of the predicate That is you will not see anything until control comes back to this predicate at either the Exit port or the Fail port Skip is particularly useful while creeping since it guarantees that control will be returned after the possibly complex execution within the box If you skip then no message at all will appear until control returns This includes calls to predicates with spy points set they will be masked out during the skip No debugging information is being collected while skipping If you supply an integer argument then this should denote an invocation number of an ancestral goal The system tries to get you to the Exit or Fail port of the invocation box you have specified out is a shorthand for skipping to the Exit or Fail port of the immediate ancestor goal If you supply an integer argument n it denotes skipping to the Exit or Fail port of the nth ancestor goal quasi skip is like a combination of leap and skip execut
404. nd to the value of the atom when the method returns Prolog chars Java StringBuffer The argument should be an unbound variable The Java method will receive an object of type StringBuffer which can be modified The argument will be bound to a list of the character codes of the StringBuffer object Prolog string Java StringBuffer The argument should be an unbound variable The Java method will receive an object of type StringBuffer which can be modified The argument will be bound to an atom converted from the StringBuffer object Prolog integer Java int MO The Java method should return an int The value will be converted to a Prolog integer Prolog byte Java byte M The Java method should return a byte The value will be converted to a Prolog integer Prolog short Java short M The Java method should return a short The value will be converted to a Prolog integer Chapter 9 Mixing Java and Prolog 171 Prolog long Java long M The Java method should return a long The value will be converted and possibly truncated to a Prolog integer Prolog float Java float MO The Java method should return a float The value will be converted to a Prolog float Prolog double Java double M The Java method should return a double The value will be converted to a Prolog float Prolog term Java SPTerm M The Java method should return an object of class SPTerm which will be converte
405. nded predicate s Note that it is possible to call consult user and then enter a patch directly on the terminal ending with D This is only recommended for small tentative patches File Files This is a shorthand way of consulting a list of files The case where there is just one filename in the list was described earlier see Section 1 2 Reading In page 11 To compile a program in core use the built in predicate compile Files where Files is specified just as for consult 1 The effect of compile 1 is very much like that of consult 1 except all new procedures will be stored in compiled rather than consulted form However predicates declared as dynamic see below will be stored in consulted form even though compile 1 is used To compile a program into an object file use the built in predicate fcompile Files where Files is specified just as for consult 1 For each filename in the list the compiler will append the suffix pl to it and try to locate a source file with that name and compile it to an object file The object filename if formed by appending the suffix ql to the specified name Chapter 5 Loading Programs 53 The internal state of SICStus Prolog is not changed as result of the compilation See Section 5 3 Considerations page 58 To load a program from a set of object files use the built in predicate load Files where Files is either a single object filename speci
406. nds for the standard input or output stream depending on context Variants of this predicate are used by all predicates that refer to filenames for resolving these Predicates that load code require that the specified file exist possibly with a pl or ql extension file_search_path Alias Expansion user file search path Alias Expansion A hook predicate This predicate specifies a set of possible file name expansions to be tried when a file specification of the form Alias Name is used in a predicate that accepts a filename argument Alias and Name must be atoms There are two possible cases for Expansion 90 SICStus Prolog e Expansion is an atom In this case the filename expands to Expansion Name which is subject to further expansion if the resulting atom begins with or see Section 7 1 Input Output page 71 e Expansion is a compound term NewAlias NewName In this case the filename expands to NewAlias NewName Name which is subject to further expansion via a recursive call to user file_search_path 2 Since it is possible to have multiple definitions for the same alias predicates such as compile 1 may have to explore several alternative expansions before they locate the file to compile Predicates such as compile 1 look for a file with a pl suffix as well as for a file without the suffix load 1 looks for a file with a ql suffix Aliases are useful in writing portable code as the
407. ne RR CE 17 access driven programming ooooococoooccccoo m 340 alias le NAM ore eer 12 89 all sol tions dou VIRI PURUS 117 ancestor goal 25s ccce keen Rocio moa ea 64 anonymous variable sseesseese sess 28 ANSI conformance 00 cece eee ee eee 6 127 anti unifications g AEN E eee 205 NP Vite code ace alten dat wees e aye A nee ape ep oa 127 arguments command line sese 7 ATA MEC ene lateness v D a 94 ALLY sikelele tare P ADU M 28 arrays c cob buone Bee ee el yet Be tun ue 189 assignment destructive eee ee 113 association lists 0 00 00 cece 191 asynchronous predicate 00 eee e eee ee ee 46 asynchronously calling Prolog 142 COM us Sure ene E neg SR aod one nate a tug done ae ae 28 attribute declaration 00 200 co 193 attributed variables 0 2 0 2 193 attributes object cece eee eee eens 327 attributes object implementation 345 B backtracking ata 35 binaty trees ope er eet pe C BRI enar 219 blackboard nia o 46 116 block declaration oooooooccooccorcccorcc 55 blo ked goal mere RR Run eke 64 DOG Yas cese Iu aos emot Nen dn putet d eru amen 30 Dread 16 built in predicate 0 00 eee eee eee 32 C call m 178 calling Prolog asynchronously oooooooooooo 142 calling Prolog from C 0 cece cece eee 141 cavalier pred
408. ng From The Top Level To exit from the top level and return to the shell either type D at the top level or call the built in predicate halt 0 or use the e exit command following a C interruption 1 9 Nested Executions Break and Abort The Prolog system provides a way to suspend the execution of your program and to enter a new incarnation of the top level where you can issue directives to solve goals etc This is achieved by issuing the directive see Section 1 7 Execution page 15 break This invokes a recursive top level indicated by the message Break level 1 You can now type queries just as if you were at top level If another call of break 0 is encountered it moves up to level 2 and so on To close the break and resume the execution which was suspended type D The debugger state and current input and output streams will be restored and execution will be resumed at the predicate call where it had been suspended after printing the message Chapter 1 How to Run Prolog 17 End break Alternatively the suspended execution can be aborted by calling the built in predicate abort 0 A suspended execution can be aborted by issuing the directive abort within a break In this case no D is needed to close the break all break levels are discarded and the system returns right back to top level I O streams remain open but the debugger is switched off abort O may also be called from within a program
409. nifiable abolish Preds Makes the predicate s specified by Preds undefined abolish Atom Arity Makes the predicate specified by Atom Arity undefined abort Aborts execution of the current directive returns to C in recursive calls to Prolog from C absolute file name RelativeName AbsoluteName AbsoluteName is the full pathname of RelativeName arg ArgNo Term Arg The argument ArgNo of the term Term is Arg assert Clause assert Clause Ref Asserts clause Clause with unique identifier Ref asserta Clause asserta Clause Ref Asserts Clause as first clause with unique identifier Ref assertz Clause assertz Clause Ref Asserts Clause as last clause with unique identifier Ref at end of line at_end_of_line Stream The end of stream or end of line has been reached for Stream or from the current input stream at_end_of_stream at_end_of_stream Stream The end of stream has been reached for Stream or from the current input stream atom X X is currently instantiated to an atom Summary of Built In Predicates 381 atom_chars Atom CharList atom_chars Atom CharList The name of the atom Atom is the list of characters CharList atomic X X is currently instantiated to an atom or a number bagof Template Goal Bag Bag is the bag of instances of Template such that Goal is satisfied not just provable block Specs Not a built in predicate block declaration bb_delete
410. nite Domains 277 P Q True if the constraints P and Q are both true PH Q True if exactly one of the constraints P and Q is true P Q True if at least one of the constraints P and Q is true P gt Q Q lt P True if the constraint Q is true or the constraint P is false P lt gt Q True if the constraints P and Q are both true or both false Note that the reification scheme introduced in Section 30 2 3 Reified Constraints page 274 is a special case of a propositional constraint 30 3 4 Combinatorial Constraints The constraints listed here are sometimes called symbolic constraints They are currently not reifiable count Val List RelOp Count where Val is an integer List is a list of integers or domain variables Count an integer or a domain variable and RelOp is a relational symbol as in Section 30 3 1 Arithmetic Constraints page 275 True if N is the number of elements of List that are equal to Val and N RelOp Count Thus count 4 is a generalization of exact1y 3 not an exported constraint that was used in an example earlier count 4 maintains domain consistency see Section 30 7 The Constraint System page 283 element X List Y where X and Y are integers or domain variables and List is a list of integers or domain variables True if the X th element of List is Y Operationally the domains of X and Y are constrained so that for every element in the domain of X there is a compatible
411. ns the worker identity as a non negative integer Also available as a read only Muse flag void muse_init_lock int lock void muse_lock int lock void muse_un_lock int lock The muse_lock and muse_un_lock functions is used to implement mutual exclusion regions Note the actual locks in Muse may not be int but they are of equal or smaller size A Muse lock must be initialized with muse_init_lock before it can be used In Muse dynamic memory allocation is performed in shared memory To allocate worker private memory it is recommended as worker_counters in Section 10 5 9 Muse FLI Example page 184 to allocate an array of size muse_max_workers that is indexed by the worker id muse_worker_ id 8 7 Hooks The user may define functions to be called at certain occasions by the Prolog system This is accomplished by passing the functions as arguments to the following set hook functions The functions can be removed by passing a NULL typedef int SP_ReadHookProc int fd SP_ReadHookProc SP_set_read_hook SP_ReadHookProc The installed function is called before reading a character from fd provided it is asso ciated with a terminal device This function shall return nonzero when there is input available at fd It is called repeatedly until it returns nonzero Not available in Muse typedef void SP_VoidFun void SP_VoidFun SP_set_reinit_hook SP_VoidFun The installed function is called upon abort and reinitialization
412. nsigned float atom name functor name Syntax of Tokens as Character Strings By default SICStus Prolog uses the ISO 8859 1 character set standard but will alternatively sup port the EUC Extended UNIX Code standard This is governed by the value of the environment variable SP CTYPE see Section 1 1 Start page 7 The character categories used below are defined as follows in the two standards layout char In ISO 8859 1 these are character codes 0 32 and 127 159 In EUC these are character codes 0 32 and 127 The common subset includes characters such as TAB LFD and SPC small letter In ISO 8859 1 these are character codes 97 122 223 246 and 248 255 In EUC these are character codes 97 122 and 128 255 The common subset includes the letters a through z capital letter In ISO 8859 1 these are character codes 65 90 192 214 and 216 222 In EUC these are character codes 65 90 The common subset is the letters A through Z Full Prolog Syntax 399 digit In both standards these are character codes 48 57 i e the digits 0 through 9 symbol char In ISO 8859 1 these are character codes 35 36 38 42 43 45 47 58 60 64 92 94 96 126 160 191 215 and 247 In EUC these are character codes 35 36 38 42 43 45 47 58 60 64 92 94 96 and 126 The common subset is 7 lt S gt 6 2 2OHSK solo char In both standards these are character codes 33 and 59 i e the characters and
413. nstraint 2 findall constraints 3 insert constraint 2 remove constraint 1 notify constrained 1 The only other CHR specific runtime error is 316 SICStus Prolog CHR ERROR registering New module Module already hosts 01d An attempt to load a second handler New into module Module already hosting handler Old was made The following exceptional conditions are detected by the CHR compiler CHR Compiler ERROR syntax rule lt N gt lt Term gt If the N th Term in the file being loaded violates the CHR syntax see Section 31 3 3 CHR Syntax page 309 CHR Compiler ERROR too many general heads in lt Name gt Unspecific heads in definitions like C V 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 lt Name gt does not qualify Currently this only happens if lt Pragma gt is unbound CHR Compiler ERROR found head lt F A gt in lt Name gt expected one of lt F A list gt Rule Name has a head of given F A which is not among the defined constraints CHR Compiler ERROR head identifiers in lt Name gt are not unique variables The identifiers to refer to individual constraints heads via in rule lt Name gt do not meet the indicated requirements CHR Compiler ERROR no handler defined CHR specific language elements declarations or rules for example
414. ntation The exceptions are 1 bookkeeping of local work each time a choicepoint is created 2 testing for signals at predicate calls and 3 synchronizing with other workers when taking work from a shared public choicepoint The overhead for doing this is some few percent making Muse nearly as efficient as sequential SICStus Prolog When a worker Q runs out of work it must interrupt some busy worker P to get work All of P s private choicepoints are then made public and the difference between P s and Q s state is copied from P to Q Q can then simply simulate failure to backtrack for work 3 3 2 Scheduling The two main functions of the scheduler are to maintain the sequential semantics of Prolog and to match idle workers with the available work with minimal overhead The sources of overhead in the Muse model include 1 copying a part of worker state 2 making local choicepoints sharable and 3 grabbing a piece of work a task from a shared choicepoint Other important scheduling issues are to maximize the grain size of computations and to prefer promising work over less promising work see Section 3 3 3 Muse Exe Cut page 44 44 SICStus Prolog 3 3 3 Cut Side Effects and Suspension Cut has a semantics strictly compatible with sequential Prolog Sometimes a cut may be partly invalid due to the fact that the current branch may be pruned by another cut of smaller scope Hausman 90 In this case the worker execu
415. nterface for inspecting execution profiles It is available as a library module see Chapter 35 Gauge Intro page 367 The original version of the profiling package was written by M M Gorlick and C F Kesselman at the Aerospace Corporation Gorlick amp Kesselman 87 Profiling is not available in Muse Only compiled code can be instrumented To get an execution profile of a program the compiler must first be told to produce instrumented code This is done by issuing the directive prolog_flag compiling _ profiledcode after which the program to be analyzed can be compiled as usual Any new compiled code will be instrumented while the compilation mode flag has the value profiledcode The profiling data is generated by simply running the program The predicate profile_data 4 see below makes available a selection of the data as a Prolog term The predicate profile_reset 1 zeroes the profiling counters for a selection of the currently instrumented predicates 122 SICStus Prolog profile_data Spec Selection Resolution Data Data is profiling data collected from the predicates covered by Spec which has the same form as for spy 1 see Section 6 3 Spy Point page 62 The Selection argument determines the kind of profiling data to be collected If unin stantiated the predicate will backtrack over its possible values which are calls All instances of entering a clause by a procedure call are counted This is equivalent t
416. o counting all procedure calls that have not been determined to fail by indexing on the first argument backtracks All instances of entering a clause by backtracking are counted choice_points All instances of creating a choicepoint are counted This occurs roughly when the implementation determines that there are more than one possibly matching clauses for a procedure call and when a disjunction is entered shallow_fails Failures in the if part of if then else statements and in the guard part of guarded clauses are counted as shallow failures See Section 10 4 If Then Else page 178 deep fails Any failures that do not classify as shallow as above are counted as deep failures The reason for distinguishing shallow and deep failures is that the former are considerably cheaper to execute than the latter execution time The execution time for the selected predicates clauses or disjuncts is es timated in artificial units The Resolution argument determines the level of resolution of the profiling data to be collected If uninstantiated the predicate will backtrack over its possible values which are predicate Data is a list of Module PredName Count where Count is a sum of the corresponding counts per clause clause Data is a list of Module ClauseName Count where Count includes counts for any disjunctions occurring inside that clause Note however that the selections calls and backtracks do not include coun
417. o raise an exception the default See Section 7 5 Exception page 101 debug The debugger is switched on in leap mode See Section 6 2 Basic Debug page 61 Chapter 7 Built In Predicates 121 trace The debugger is switched on in creep mode See Section 6 2 Basic Debug page 61 zip The debugger is switched on in zip mode See Section 6 2 Basic Debug page 61 nodebug notrace nozip The debugger is switched off See Section 6 2 Basic Debug page 61 leash Mode Leashing Mode is set to Mode See Section 6 2 Basic Debug page 61 spy Spec Spy points are placed on all the predicates given by Spec See Section 6 3 Spy Point page 62 nospy Spec Spy points are removed from all the predicates given by Spec See Section 6 3 Spy Point page 62 nospyall Removes all the spy points that have been set debugging Displays information about the debugger See Section 6 2 Basic Debug page 61 7 15 Execution Profiling Execution profiling is a common aid for improving software performance The SICStus Prolog compiler has the capability of instrumenting compiled code with counters which are initially zero and incremented whenever the flow of control passes a given point in the compiled code This way the number of calls backtracks choicepoints created etc can be counted for the instrumented predicates and an estimate of the time spent in individual clauses and disjuncts can be calculated Gauge is a graphical user i
418. ocked on these variables see Section 2 3 Procedural page 34 asserta Clause ISO asserta Clause Ref Like assert 2 except that the new clause becomes the first clause for the predicate concerned assertz Clause ISO assertz Clause Ref Like assert 2 except that the new clause becomes the last clause for the predicate concerned clause Head Body ISO clause Head Body Ref clause Head Body Ref The clause Head Body exists in the current interpreted program and is uniquely identified by Ref The predicate concerned must currently be dynamic At the time of call either Ref must be instantiated to a valid identifier or Head must be instantiated to an atom or a compound term Thus clause 3 can have two different modes of use retract Clause ISO The first clause in the current interpreted program that matches Clause is erased The predicate concerned must currently be dynamic retract 1 may be used in a non determinate fashion i e it will successively retract clauses matching the argument through backtracking If reactivated by backtracking invocations of the predicate whose clauses are being retracted will proceed unaffected by the retracts This is also true for invocations of clause 2 3 for the same predicate The space occupied by a retracted clause will be recovered when instances of the clause are no longer in use Chapter 7 Built In Predicates 115 retractall Head Erases all
419. ode 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 31 3 3 CHR Syntax page 309 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 handling of operator declarations in particular during fcompile 1 operator 3 declarations with the same denotation as op 3 but taking effect during compilation and loading are helpful Example Chapter 31 Constraint Handling Rules 309 operator 700 xfx operator 600 xfx 31 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
420. of characters Thus format Hello world has the same effect as 84 SICStus Prolog format Hello world format 2 and format 3 is a Prolog interface to the C stdio function printf It is modeled after and compatible with Quintus Prolog Arguments is a list of items to be printed If there are no items then an empty list should be supplied The default action on a format character is to print it The character introduces a control sequence To print a repeat it format Hello world will result in Hello world The escape sequence see Escape Sequences page 401 c c for continue is use ful when formatting a string for readability It causes all characters up to but not including the next non layout character to be ignored format Hello Nc world will result in Hello world The general format of a control sequence is NC The character C determines the type of the control sequence N is an optional numeric argument An alternative form of N is implies that the next argument in Arguments should be used as a numeric argument in the control sequence Example format Hello 4cworld 0 x and format Hello cworld 4 0 x both produce Helloxxxxworld The following control sequences are available eoru a The argument is an atom The atom is printed without quoting Ne Print character The argument is a number
421. off in dicates that the interrupt mechanism is turned off for Stream Any other atom is the name of a predicate invoked when something is readable on Stream The handler predicate has one argument the stream that is readable For example Stream interrupt Stream _ int handler will enable the interrupt mechanism Given the predicate int_handler Stream read Stream Data write Data nl the term read from Stream will be written to the current output Note there is no guarantee that a complete Prolog term is available yet If not read 2 will suspend as usual Not available in Muse Not available in operating systems that do not provide the ability to generate signals when new data becomes available on a file descriptor Chapter 7 Built In Predicates 93 7 1 6 DEC 10 Prolog File I O The following predicates manipulate files see File The file File becomes the current input stream File may be a stream previously opened by see 1 or a filename If it is a filename the following action is taken If there is a stream opened by see 1 associated with the same file already then it becomes the current input stream Otherwise the file File is opened for input and made the current input stream seeing FileName FileName is unified with the name of the current input file if it was opened by see 1 with the current input stream if it is not user_input otherwise with user seen Closes the current input stream and resets i
422. old value We assume that Goal does not produce any false solutions that would be eliminated by cuts in a sequential execution Thus Goal may need to include redundant checks to ensure that its solutions are valid as discussed above maxof Value Goal _ bb_put max 1 4 initialize max so far call Goal update_max Value fail maxof _ _ Max bb_delete max Max Max gt 1 update max New repeat bb get max Old compare C Old New update max C Old New update max Old New bb update max Old New update max 2 _ _ update_max gt _ _ 7 12 All Solutions When there are many solutions to a problem and when all those solutions are required to be collected together this can be achieved by repeatedly backtracking and gradually building up a list of the solutions The following built in predicates are provided to automate this process Note that the Goal argument to the predicates listed below is called as if by ca11 1 at runtime Thus if Goal is complex and if performance is an issue define an auxiliary predicate which can then be compiled and let Goal call it 118 SICStus Prolog setof Template Goal Set ISO Read this as Set is the set of all instances of Template such that Goal is satisfied where that set is non empty The term Goal specifies a goal or goals as in call Goal see Section 7 4 Control page 99 Set is a set of terms represented as a li
423. olog page 167 However this will most likely be extended in the future The library does not yet define any predicates However it must be loaded to make sure that the JVM the Java Virtual Machine is loaded correctly and that the interface code has access to all relevant references to the JVM It is loaded by the query use module library jasper This will dynamically load the JVM into memory and initialize the JNI Invocation API There is also an directory of examples of how to use Jasper library jasper examples 372 SICStus Prolog Chapter 38 Glue Code Generator 373 38 Glue Code Generator This chapter describes utilities useful for generating glue code for the Foreign Language Inter face when building statically linked Runtime Systems or Development Systems see Section 8 2 5 Interface Predicates page 133 This library module can be loaded by the query use module library flinkage and refers to the following shared object files or DLLs runtime kernel The SICStus runtime kernel usually SP_PATH libsprt37 so under UNIX or A5P_PATHA sprt37 d11 under Windows and development kernel The SICStus development kernel usually SP_PATH libspds37 so under UNIX or SP_PATH N spds37 d11 under Windows The following predicate can be used to generate a glue code file flinkage c file out of any old style foreign_file 2 and foreign 2 3 declarations found in
424. olog They cannot be reified On a lower level new primitive constraints can be defined with indexicals In this case they take part in the basic constraint solving algorithm and express custom designed rules for special cases of the overall local propagation scheme Such constraints are called FD predicates see Section 30 9 Defining Primitive Constraints page 290 They can optionally be reified 30 4 Enumeration Predicates As is usually the case with finite domain constraint solvers this solver is not complete That is it does not ensure that the set of posted constraints is satisfiable One must resort to search enumeration to check satisfiability and get particular solutions The following predicates provide several variants of search indomain X where X is a domain variable with finite bounds or an integer Assigns in increasing order via backtracking a feasible value to X minimize Goal X maximize Goal X Uses a branch and bound algorithm with restart to find an assignment that minimizes maximizes the domain variable X Goal should be a Prolog goal that constrains X to become assigned and could be a 1abeling 2 goal The algorithm calls Goal repeatedly with a progressively tighter upper lower bound on X until a proof of optimality is obtained at which time Goal and X are unified with values corresponding to the optimal solution labeling Options Variables where Variables is a list of domain variables or
425. om cider bi11 jan tom Variables occurring in Goal will not be treated as free if they are explicitly bound within Goal by an existential quantifier An existential quantification is written Y Q meaning there exists a Y such that Q is true where Y is some Prolog variable For example setof X Y likes X Y S would produce the single result Chapter 7 Built In Predicates 119 S bill dick harry jan tom in contrast to the earlier example bagof Template Goal Bag ISO This is exactly the same as setof 3 except that the list or alternative lists returned will not be ordered and may contain duplicates The effect of this relaxation is to save a call to sort 2 which is invoked by setof 3 to return an ordered list X P The all solution predicates recognize this as meaning there exists an X such that P is true and treats it as equivalent to P see Section 7 4 Control page 99 The use of this explicit existential quantifier outside the setof 3 and bagof 3 constructs is superfluous and discouraged findall Template Goal Bag ISO Bag is a list of instances of Template in all proofs of Goal found by Prolog The order of the list corresponds to the order in which the proofs are found The list may be empty and all variables are taken as being existentially quantified This means that each invocation of findall 3 succeeds exactly once and that no variables in Goal get bound Avoiding the manag
426. om a C double int SP put atom SP term ref t unsigned long a Assigns to t a Prolog atom from a which must be the canonical representation of a Prolog atom see Section 8 2 Calling C page 128 int SP put string SP term ref t char name Assigns to t a Prolog atom from a C string int SP put address SP term ref t void pointer Assigns to t a Prolog integer from a C pointer The pointer must be NULL or an address having the four most significant bits in common with addresses returned by malloc This excludes pointers to automatic C variables 138 SICStus Prolog i e addresses to the C stack Furthermore the address must be aligned on a four bytes boundary NULL is converted to the integer 0 int SP_put_list_chars SP_term_ref t SP_term_ref tail char s Assigns to t a Prolog list of the character codes in s The list is terminated by the value of tail int SP_put_list_n_chars SP_term_ref t SP term ref tail long n char s Assigns to t a Prolog list of the first n character codes or zeroes in s The list is terminated by the value of tail int SP put number chars SP term ref t char s Assigns to t a Prolog number by parsing the string in s int SP put functor SP term ref t unsigned long name int arity Assigns to t a Prolog compound term with all the arguments unbound variables If arity is 0 assigns the Prolog atom whose canonical representation is name to t This is similar to calling functor 3
427. oms or strings has special meaning and indi cates the start of an escape sequence see Escape Sequences page 401 This flag is relevant when reading as well as when writing terms and is initially on on or off Turns raising of exception on file errors on or off Equiva lent to fileerrors 0 and nofileerrors O respectively see Section 7 1 5 Stream Pred page 89 Initially on on or off Turns garbage collection of the global stack on or off Initially on Margin Number of kilobytes If less than Margin kilobytes are reclaimed in a garbage collection of the global stack then the size of the global stack should be increased Also no garbage collection is attempted unless the global stack is at least Margin kilobytes Initially 500 Governs global stack garbage collection trace messages verbose Turn on verbose tracing of garbage collection terse Turn on terse tracing of garbage collection off Turn off tracing of garbage collection the default redefine warnings on or off Enable or disable warning messages when a predicate is being e redefined from a different file than its previous definition e imported to the user module and it was previously locally defined e redefined locally and it was previously imported e imported to the user module from another module than it was previ ously imported from Initially on This warning is always disabled in Runtime Systems single var warnings unknown on or off
428. one could pass parameters to an object as follows using the method augment 1 vehicle augment new_attrs Instance Attribute_list self new Instance assign list Attribute list Instance amp assign list Instance amp assign list Att List Instance assign Att Instance assign list List Instance amp assign P Instance Instance assert P n yes 4 create a new truck vehicle new attrs truck capacity total_weight yes 32 6 Access Driven Programming Daemons Access based programming is a paradigm where certain actions are performed or some constraints are checked when access operations are invoked Access operations for updates i e assert retract can be redefined in an object by redefining these operations and delegating the same operation to super Notice that without a delegation mechanism this would not be possible since the Self would have changed So assume that we want to print on the screen p is augmented whenever the fact p X is asserted in an object foo we just redefine assert 1 foo 1 super object amp dynamic p 1 amp p 0 Y p 1 amp assert p X assert 1 is redefined for p X super lt assert p X display p is augmented ttynl amp Chapter 32 Prolog Objects 341 assert M delegating assert _ messages super lt assert M amp 32 7 Instances Objects are relative
429. ons by back tracking but creates choicepoints only if necessary 28 2 Examples 28 2 1 Example 1 sat X Y sat X _A Y Y illustrates three facts First any accumulated constraints affecting the top level variables are displayed as floundered goals since the query is not true for all X and Y Secondly accumulated constraints are displayed as sat V Expr or sat V Expr where V is a variable and Expr is a polynomial i e an exclusive or of conjunctions of variables and constants Thirdly _A had to be introduced as an artificial variable since Y cannot be expressed as a function of X That is X Y is true iff there exists an _A such that X _A Y Y Let s check it taut _A X _A Y Y X Y T T 1 verifies the above answer Notice that the formula in this query is a tautology and so it is entailed by an empty set of constraints Chapter 28 Boolean Constraint Solver 243 28 2 2 Example 2 taut A lt C T no sat A lt B sat B lt C taut A lt C T T 1 sat A _A _B C sat B _B C taut a T T 0 yes taut a T T 0 illustrates the entailment predicate In the first query the expression A implies C is neither known to be true nor false so the query fails In the second query the system is told that A implies B and B implies C so A implies C is entailed The expressions in the third and fourth queries a
430. ontains an attribute declaration Query Vars is the list of variables occurring in the query or in terms bound to such variables and AttrVars is a list of possibly attributed variables created during the execution of the query The two lists of variables may or may not be disjoint If the attributes on AttrVars can be interpreted as constraints this predicate will typ ically project those constraints onto the relevant QueryVars Ideally the residual constraints will be expressed entirely in terms of the QueryVars treating all other vari ables as existentially quantified Operationally project_attributes 2 must remove all attributes from AttrVars and add transformed attributes representing the projected constraints to some of the Query Vars Projection has the following effect on the Prolog top level When the top level query has succeeded project attributes 2 is called first The top level then prints the answer substition and residual constraints While doing so it searches for attributed variables created during the execution of the query For each such variable it calls attribute goal 2 to get a printable representation of the constraint encoded by the attribute Thus project attributes 2 is a mechanism for controlling how the resid ual constraints should be displayed at top level Similarly during the execution of call residue Goal Residue when Goal has suc ceeded project attributes 2 is called After that all attribute
431. ook up connected 3 if pred SP predicate connected 3 fprintf stderr Could not find connected 3 n exit 1 Create the three arguments to connected 3 SP_put_string from SP_new_term_ref Stockholm SP_put_string to SP_new_term_ref Orebro SP_put_variable path SP_new_term_ref Open the query In a development system the query would look like connected Stockholm Orebro X Chapter 8 Mixing C and Prolog 159 if goal SP open query pred from to path fprintf stderr Failed to open query n exit 1 Loop through all the solutions while SP next solution goal 1 printf Path write path path SP_close_query goal exit 0 Create the saved state containing the Prolog code sicstus SICStus 3 7 Tue Jun 02 12 29 02 MET DST 1998 compile train compiling home jojo sicstus examples train pl home jojo sicstus examples train pl compiled 40 msec 2848 bytes yes save_program train sav SIcStus state saved in home jojo sicstus examples train sav yes halt Create the executable using spmkrs spmkrs train c train c SICStus 3 7 Tue Jun 02 12 29 02 MET DST 1998 var tmp aaaOch9LZ c generated 0 msec yes And finally run the executable train Path Stockholm gt Katrineholm gt Hallsberg gt Kumla gt Orebro Path Stockholm gt Vaste
432. option the call muse_trace Query is used for running the query Query with tracing After the query is run there will be a file with extension mt containing a trace of the last query execution The distribution only contains the Sun 4 executable It can be used both under SunOS 4 x Solaris 1 x and SunOS 5 x Solaris 2 x The program itself has a dialog box to request the filename of the trace file or you can just specify the file on the command line 3 4 2 Visandor The Visandor graphics tracing program was originally developed for the amp Prolog system Hermenegildo and Greene 90 It is supplied in binary executable form for Sun 4 com puters More information about that tool and related work is available via WWW from http www clip dia fi upm es or via email from lt clip clip dia fi upm es gt The mt2vt tool may be used for converting a Must file to a Visandor file with extension vt 3 4 3 Vimust The Must and Visandor tools can be combined into the Vimust tool If the Must file with extension mt and its corresponding Visandor file with extension vt both exist they can the be viewed together with the vimust tool 3 5 Programming Considerations It is possible to control the parallelism of a program by means of parallel and sequential declarations see Section 5 2 Declarations page 53 Sequential declarations may be necessary to prevent infinite loops in certain programming construc
433. or as its principal functor 5 The character within a string must be written duplicated Similarly for the character within a quoted atom 6 Backslashes in strings quoted atoms and integers written in 0 notation denote escape sequences 7 A name token declared to be a prefix operator will be treated as an atom only if no term read in can be read by treating it as a prefix operator 8 A name token declared to be both an infix and a postfix operator will be treated as a postfix operator only if no term read in can be read by treating it as an infix operator Standard Operators 403 Standard Operators op op op op op op op op op op op op op op 1200 1200 1150 1100 1050 1000 900 700 550 500 500 400 300 200 xfx fx fx xfy xfy xfy fy xfx xfy yfx fx yfx xfx xfy gt DD mode public dynamic volatile multifile block meta_predicate parallel sequential Esas gt D spy nospy is 0 lt gt lt gt 72 198 ms dh PNE F5 194 lt lt gt gt 1 mod D 404 SICStus Prolog References 405 References Aggoun amp Beldiceanu 92 A Aggoun and N Beldiceanu Extending CHIP in order to Solve Complex Schedul ing and Placement Problems Mathl Comput Modelling
434. ormat e esses eere 362 34 2 TE tO PLOP it ret NR Re PSOINECERE S GRE SOR 363 oA TEE ete A RERIBRG RAE AN RI RUP READER DUE Ed 364 35 The Gauge Profiling Tool 367 36 I O on Lists of Character Codes 369 OC LII PEE 371 38 Glue Code Generator sue 373 39 Timeout Predicate uuueesuuss 375 40 Cross Reference Producer 377 Summary of Built In Predicates 379 Bull Prolog Syntax rita CAE ixi 395 INOLaT10I x3 tt ea Rio toed Be AE ae eS 395 Syntax of Sentences as Terms 0 eee cece ee 396 Syntax of Terms as Tokens 0 eect eee 397 Syntax of Tokens as Character Strings 0 cece ee eee eee ee 398 Escape Seq ences ze a een ee ad need Dae e Spe et 401 NOTES OP EPUM DE RP ERREUR 402 1x x SICStus Prolog Standard Operators ex rer caos 403 A PV EX DN PE Paw vrbe a d a 405 Predicate Index cidad 409 Prolog Objects Method Index 421 Concept Idea ee peut nt ad bats 423
435. ost hook is intended to be used to do things which may require that all streams have been created 8 5 3 3 User stream Hook Example This section contains an example of how to create and install a set of user streams The hook is set by calling SP_set_user_stream_hook in the main program like this SP_set_user_stream_hook SP_UserStreamHook user_strhook Remember SP_set_user_stream_hook and SP_set_user_stream_post_hook must be called before SP_initialize The hook user_strhook is defined like this SP_stream user_strhook int std_fd SP_stream s SP_make_stream NULL my_getc my_putc my_flush my_eof my_clrerr NULL amp s return s 5 See Section 8 5 2 2 Installing a New Stream page 147 for a description on the parameters to SP_make_stream 150 SICStus Prolog 8 6 Muse Support Functions Dynamic loading of foreign language functions must be done when the system is adjusted to one worker If you use dynamic linking it is not recommended to use C global or static local variables It is platform dependent if the variables are shared among workers or private If static linking is used the variables become private Some useful Muse C functions int muse_max_workers void Returns the maximum number of workers Also available as a read only Muse flag int muse_num_workers void Returns the actual number of allocated workers Also available as a writable Muse flag int muse_worker_id void Retur
436. out mechanism is disabled that is eternal waiting The latter form is the timeout time out Tuple Places the tuple Tuple in Linda s tuple space in Tuple Removes the tuple Tuple from Linda s tuple space if it is there If not the predicate blocks until it is available that is someone performs an out 1 in noblock Tuple Removes the tuple Tuple from Linda s tuple space if it is there If not the predicate fails This predicate can fail due to a timeout in TupleList Tuple As in 1 but succeeds when either of the tuples in TupleList is available Tuple is unified with the fetched tuple If that unification fails the tuple is not reinserted in the tuple space rd Tuple Succeeds if Tuple is available in the tuple space suspends otherwise until it is available Compare this with in 1 the tuple is not removed rd noblock Tuple Succeeds if Tuple is available in the tuple space fails otherwise This predicate can fail due to a timeout 234 SICStus Prolog rd TupleList Tuple As in 2 but does not remove any tuples bagof_rd_noblock Template Tuple Bag Bag is the list of all instances of Template such that Tuple exists in the tuple space The behavior of variables in Tuple and Template is as in bagof 3 The variables could be existentially quantified with 7 2 as in bagof 3 The operation is performed as an atomic operation This predicate can fail due to a timeout Example Assume that only one client
437. output from the process is piped to Stream In the latter case the input to the process is piped from Stream Stream may be read written using the ordinary StreamIO predicates It must be closed using close 1 it is not closed automatically when the process dies rename_file OldName NewName OldName is the name of an existing file or directory which will be renamed to New Name If the operation fails an exception is raised shell Starts a new interactive shell named by the environment variable SHELL The control is returned to Prolog upon termination of the shell process shell Command Passes Command to a new shell named by the environment variable SHELL for execu tion Succeeds if the return status value is 0 On MSDOS Windows or OS 2 if SHELL is defined it is expected to name a UNIX like shell which will be invoked with the argument c Command If SHELL is undefined the shell named by COMSPEC will be invoked with the argument C Command shell Command Status Passes Command to a new shell named by the environment variable SHELL for execu tion The status value is returned in Status See also she11 1 above sleep Seconds Puts the SICStus Prolog process asleep for Second seconds system Starts a new interactive default shell process The control is returned to Prolog upon termination of the shell process system Command Passes Command to a new default shell process for execution Succeeds if the return status value
438. p print bounds Terminal get bounds XO X1 YO Y1 Terminal bh point 4 super history point amp super bounded point amp format xbounds d d Nc ybounds d d n X0 X1 Y0 Y1 new Instance Coords Bounds history_point lt new Instance Coords Instance move X Y bounded_point history_point move _ _ amp display Terminal bounded_point history_point set bounds Bounds amp bound constraint X Y move X Y amp display Terminal print history Terminal 354 SICStus Prolog tty 1 format X Y format X Y point at 8 12 xbounds 5 15 ybounds 5 15 with location history 8 12 9 11 32 10 3 Prolog programs Prolog is a product by LPA Associates for object oriented programming extensions of LPA Pro log Most Prolog programs can be easily converted into Prolog Objects programs The following is a translation of a program for fault diagnosis in LPA s Prolog manual page 83 The program illustrates a top down diagnosis method starting from general objects to more specific objects The problem is fault diagnosis for car maintenance The objects have the following structure faults electrical lights starting starter motor sparking plugs distributer fuel system mechanical The general diagnosis method is defined in the object faults whereas the cause effect relationships
439. p Macintosh is a trademark of Apple Computer Inc SICStus Prolog Notational Conventions 5 Notational Conventions Keyboard Characters When referring to keyboard characters printing characters are written thus a while control characters are written like this A Thus C is the character you get by holding down the CTL key while you type c Finally the special control characters carriage return line feed and space are often abbreviated to RET LFD and SPC respectively Mode Spec When introducing a built in predicate we shall present its usage with a mode spec which has the form name arg arg where each arg denotes how that argument should be instantiated in goals and has one of the following forms ArgName This argument should be instantiated to a term denoting a goal or a clause or a predicate name or which otherwise needs special handling of module prefixes ArgName This argument should be instantiated to a non variable term ArgName This argument should be uninstantiated ArgName This argument may or may not be instantiated Mode specs are not only used in the manual but are part of the syntax of the language as well When used in the source code however the ArgName part must be omitted That is arg must be either or Predicate Spec In the context of certain compiler declarations we shall need the following notation Predicates in Prolog are distinguished by their name and their arity
440. perator declarations Same as write_term Stream Term numbervars true display Term The term Term is displayed onto the standard output stream which is not necessarily the current output stream in standard parenthesized prefix notation Same as write_ term user Term ignore_ops true write canonical Term ISO write_canonical Stream Term ISO Similar to write Stream Term The term will be written according to the standard syntax The output from write canonical 2 can be parsed by read 2 even if the term contains special characters or if operator declarations have changed Same as write term Stream Term quoted true ignore_ops true writeq Term ISO writeq Stream Term ISO Similar to write Stream Term but the names of atoms and functors are quoted where necessary to make the result acceptable as input to read 2 provided the same operator declarations are in effect Same as write_term Stream Term quoted true numbervars true print Term print Stream Term Hookable Prints Term onto Stream This predicate provides a handle for user defined pretty printing e If Term is a variable then it is output using write Stream Term e If Term is non variable then a call is made to the user defined predicate user portray 1 If this succeeds then it is assumed that Term has been out put e Otherwise print 2 is called recursively on the components of Term unless Term is atomic in w
441. pl home san pl math pl consulted 10 msec 816 bytes yes sqrt 5 0 X X 2 23606797749979 yes sqrt a X TYPE ERROR sqrt a _30 arg 1 expected number found a sqrt 5 X DOMAIN ERROR sqrt 5 0 arg 1 expected gt 0 0 found 5 0 163 The above example used the foreign language interface with dynamic linking To statically link math o with the Prolog emulator the following steps would have been taken splfr math math pl static c math c 1 lm SICStus 3 5 Sat Feb 24 00 35 37 MET 1996 tmp 00249aaa c generated 10 msec yes spmkds mathsp math SICStus 3 5 Sat Feb 24 00 35 37 MET 1996 tmp 00274aaa c generated 0 msec yes sicstus base mathsp SICStus 3 5 Sat Feb 24 00 35 37 MET 1996 math consulting home san pl math pl home san pl math pl consulted O msec 864 bytes yes sqrt 5 0 X X 2 23606797749979 164 SICStus Prolog yes 8 10 4 Stream Example This is a small example how to initialize a bidirectional socket stream error handling omitted typedef struct int fd socket number FILE r stream For reading FILE w stream For writing SocketData int socket sgetc SocketData socket return fgetc socket r stream int socket_sputc char c SocketData socket t return fputc c socket w stream int socket_sflush SocketData socket return fflush socke
442. points 00 eee eee 319 31 4 4 CHR Debugging Messages 0 ee eee 320 31 4 5 CHR Debugging Options 00 eee 320 31 5 Programming Hints eai A aa aE eee 323 31 6 Constraint Handlers 0 0 cee n 324 31 7 Backward Compatibility 0 00 cece cece ee eee 326 32 Prolog Objects cies eee eee alte ie eta res 327 321 Getting Started iy iis aii tect dice satiety he peace ER 328 32 2 Declared Objects 0 eee cece cece I 328 32 2 1 Object Declaration 000 cee ee eee eee 328 32 2 2 Method Declarations 00 eese eee eee eee 329 32 2 3 Generic Objects for Easy Reuse o oooooo ooooooo 331 32 3 Self Message Sending and Message Delegation 332 32 4 Object Hierarchies Inheritance and Modules 333 32 4 4 Inheritance 0 cece ee hn 334 32 4 2 Differential Inheritance 00 eee eee eee 335 32 4 3 Use of Modules orre eea cee ee en ee 335 32 44 Super and Sub 0 cece eee eee eee 335 32 45 The Keyword Super 00 c cece eee eee eee 336 32 4 6 Semantic Links to Other Objects 336 32 4 7 Dynamically Declared ObjectsS 0ooooomoo 336 32 4 8 Dynamic Methods 0c eese eee 337 32 4 9 Inheritance of Dynamic Behavior 338 32 5 Creating Objects Dynamically 0 eee ee ee ee 338 32 5 1 Object Creation
443. ponding to the Prolog stream Stream This predicate is only useful when streams are passed between Prolog and C Note that StreamCode no longer has any relation to the file descriptor The StreamCode is a Prolog integer representing a SP_stream pointer as described in see Sec tion 8 3 2 Creating Prolog Terms page 137 SP_put_address To write on a Prolog stream from C special versions of the most common standard C I O functions are used int SP_getc void int SP_fgetc SP_stream s void SP_putc int c void SP_fputc int c SP_stream s void SP_puts char string void SP_fputs char string SP_stream s int SP_printf char format int SP_fprintf SP_stream s char format int SP_fflush SP_stream s int SP fclose SP stream s There are three predefined streams accessible from C SP stdin Standard input Refers to the same stream as user input in Prolog Which stream is referenced by user input is controlled by the flag user input see prolog_flag 3 SP stdout Standard output Refers to the same stream as user output in Prolog Which stream is referenced by user output is controlled by the flag user output see prolog f1ag 3 SP_stderr Standard error Refers to the same stream as user_error in Prolog Which stream is referenced by user_error is controlled by the flag user_error see prolog_flag 3 SP curin Current input It is initially set equal to SP stdin It can be changed with the pr
444. predicates covered by the Specs You cannot place a spy point on an undefined predicate If you set some spy points when the debugger is switched off then it will be automatically switched on Examples spy user p m q 2 3 spy m p 1 q 11 nospy Spec Similar to spy Spec except that all the predicates given by Spec will have previously set spy points removed from them nospyall Removes all the spy points that have been set spypoint_condition Goal Port Test Sets a conditional spy point on the predicate for Goal When the debugger reaches the spy point three conditions must be met for the spy point to apply The actual goal must match Goal the actual port must match Port and Test an arbitrary Prolog goal must succeed The options available when you arrive at a spy point are described later See Section 6 5 Debug Options page 65 6 4 Format of Debugging messages We shall now look at the exact format of the message output by the system at a port 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 ENS 23 6 Call T foo hello there 123 E is only used at Exception ports and displays a pending exception N is only used at Exit ports and indicates whether the invocation could backtrack and find alter native solutions Unintended non determinism is a source of inefficiency and this annotation can 64
445. programs of any size it is clearly impractical to creep through the entire program Spy points make it possible to stop the program whenever it gets to a particular predicate which is 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 spy point on a predicate indicates that you wish to see all control flow through the various ports of its invocation boxes except during skips When control passes through any port of a invocation box 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 on every port Spy points are set and removed by the following built in predicates The first two are also standard operators spy Spec Sets spy points on all the predicates given by Spec which is is of the form Chapter 6 Debugging 63 Name all predicates called Name no matter what arity where Name is an atom for a specific name or a variable for all names or Name Arity the predicate of that name and arity or Name Low High Name Low High the predicates of that name with arity in the range Low High or Module Spec specifying a particular module see Section 4 2 Module Spec page 48 instead of the default type in module where Module is an atom for a specific module or a variable for all modules or Spec Spec the set of all
446. pted from Van Hentenryck et al 95 define important notions of consistency and entailment of constraints wrt stores 284 SICStus Prolog A ground constraint is true if it holds and false otherwise A constraint C is domain consistent wrt S iff for each variable Xi and value Vi in D Xi S there exist values Vj in D Xj S 1 lt j lt n i j such that C V1 Vn is true A constraint C is domain entailed by S iff for all values Vj in D Xj S 1 lt j lt n C V1 Vn is true Let D X S denote the interval min D X S max D X S A constraint C is interval consistent wrt S iff for each variable Xi there exist values Vj in D Xj S lt j lt n i j such that C V1 min D Xi S Vn and C V1 max D Xi S Vn are both true A constraint C is interval entailed by S iff for all values Vj in D Xj S 1 lt j lt n C V1 Vn is true Finally a constraint is domain disentailed interval disentailed by S iff its negation is domain entailed interval entailed by S 30 7 2 Pitfalls of Interval Reasoning In most circumstances arithmetic constraints only maintain interval consistency and only detect interval entailment and disentailment Note that there are cases where an interval consistency maintaining constraint may detect a contradiction when the constraint is not yet interval disentailed as the following example illustrates Note that X Y maintains domain consistency if
447. r keys in OldAssoc Chapter 14 Attributed Variables 193 14 Attributed Variables This package implements attributed variables It provides a means of associating with variables arbitrary attributes i e named properties that can be used as storage locations as well as to extend the default unification algorithm when such variables are unified with other terms or with each other This facility was primarily designed as a clean interface between Prolog and constraint solvers but has a number of other uses as well The basic idea is due to Christian Holzbaur and he was actively involved in the final design For background material see the dissertation Holzbaur 90 To load the package enter the query use_module library atts The package provides a means to declare and access named attributes of variables The attributes are compound terms whose arguments are the actual attribute values The attribute names are private to the module in which they are defined They are defined with a declaration attribute AttributeSpec AttributeSpec where each AttributeSpec has the form Name Arity There must be at most one such declaration in a module Module Having declared some attribute names these attributes can now be added updated and deleted from unbound variables For each declared attribute name any variable can have at most one such attribute initially it has none The declaration causes the following two access predic
448. raint 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 Section 29 5 Projection page 259 29 3 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 this functionality badly you should look into symbolic algebra packages Although the clp 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 nonlinear constraints you have to be aware of the fact that success is qualified modulo the existence of a solution to the system of residual nonlinear constraints clp r sin X cos X clpr sin X cos X 0 0 There are indeed infinitely many solutions to this constraint X 0 785398 n Pi but clp Q R has no direct means to find and represent them The systems goes through some lengths to recognize linear expressions as suc
449. ram but they are very useful for making programs more readily comprehensible Two forms of comment are allowed in Prolog 1 The character followed by any sequence of characters up to end of line 2 The symbol followed by any sequence of characters including new lines up to Chapter 3 Running Prolog in Parallel 41 3 Running Prolog in Parallel This chapter describes what parallel Prolog execution is about and how Muse can be used as a prolog accelerator to make programs run faster in parallel than they do sequentially 3 1 Introduction Logic programs offer many opportunities for the exploitation of parallelism the main ones being OR parallelism and AND parallelism Conery 83 Each kind has its own advantages and disadvan tages but we have chosen to focus on OR parallelism as a first step for a number of reasons From our perspective the wide range of potential applications and the very slight execution overhead have been the main reasons See Lusk et al 90 for a fuller discussion about the advantages of OR parallelism in the context of the Aurora system The goal with Muse as with Aurora has been to allow multiple processors to exploit the implicit OR parallelism of Prolog programs with a minimum of overhead preserving the full Prolog language with its standard semantics 3 2 Running a Parallel Example In this section we illustrate the parallelism in the well known 8 queens problem This code is reprodu
450. ras gt Orebro Path Stockholm gt Uppsala gt Vasteras gt Orebro 160 SICStus Prolog 8 10 2 I O on Lists of Character Codes This example is taken from the SICStus Prolog library simplified but operational A stream for writing is opened where the written characters are placed in a buffer When the stream is closed a list of character codes is made from the contents of the buffer The example illustrates the use of user definable streams The open_buf_stream function opens a stream where the characters are put in a buffer The stream is closed by stream_to_chars which returns the list constructed on the heap The Prolog code simplified foreign open_buf_stream open_buf_stream address SP_stream foreign stream to chars stream_to_chars address SP_stream term foreign resource example open buf stream stream to chars load foreign resource example with output to chars Goal Chars runs Goal with current output set to a list of characters with output to chars Goal Chars open buf stream StreamCode stream code Stream StreamCode current output CurrOut set output Stream call_and_reset Goal Stream Curr ut StreamCode Chars call and reset Goal Stream CurrOut StreamCode Chars call Goal put 0 gt stream_to_chars StreamCode Chars reset stream Stream Curr ut call and reset Stream CurrOut _ _ re
451. rates 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 Constraint 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 31 3 2 CHR Declarations page 308 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 variables 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 31 3 2 CHR Declarations page 308 find constraint Pattern Id Nondeterministically enumerates constraints from the constraint store that match Pat tern i e which are instances of Pattern Id is unified with an internal object repre senting the constraint find constraint Var Pattern Id Nondeterministically enumerates constraints from the constraint store that delay on Var and match Pattern i e which are instances of Pattern The identifier Id
452. ration volatile oooooooocoooommmor o 55 declarations 0 cece cence een eee ene 53 declarative semantics 00 0c e eee eee 33 deep failure vss pobre eek PUR EE nas 122 178 default database 0 cee eee eee eee eee 237 definite clause gpeRLERXAGN ea vd 27 delegation xa servet Serre pete haa bae 327 delegation message 6 6 cece cece eee eee 332 destructive assignment 0 0 20 eee 113 development kernel 00 020 eee 373 development system 00 00 e eee 6 156 differential inheritance 00 0005 335 directive uerb otReib eu A UE id eee deed 8 12 domain variable 00 cece eee eee 272 domain finite 1 4 i i dardo ia eee ae 272 domain consistent 0 0 00 e cece eee 284 domain disentailed 000000 e eee 284 domain entailed 00 cece eee eee eee eee 284 dynamic declaration 0000 eee ee eee 54 dynamic linking 0 e cece eee eee 129 dynamic method 00 00 e eee eee ee 337 dynamic object 00 008 327 336 338 dynamic predicate 00 00 eee eee eee 54 E eniacs interface ii if edhe cer yee ep alee hee Dial Awd 18 end Oli etc eeu ORE eee ee eines 5 end of ne uis im beruht een 92 COLO STEAM ria e paliueqeneu ei gu 91 Ing EE 5 error handling esi iei td ber an 69 101 error Syntaxiccdcviexdvukrbpe
453. re C denotes a sequence of zero or more Cs 6 A few syntactic categories have names with arguments and rules in which they appear may contain meta variables looking thus X The meaning of such rules should be clear from analogy with the definite clause grammars see Section 7 1 2 Definite page 76 7 In the section describing the syntax of terms and tokens see Term Token page 397 par ticular tokens of the category name are written thus name while tokens which are individual punctuation characters are written literally sentence clause directive non unit clause unit clause command query head body goal grammar rule gr head gr body SICStus Prolog Syntax of Sentences as Terms module sentence dist where list is a list of sentence clause directive grammar rule gt non unit clause unit clause command query head body head where head is not otherwise a sentence gt body gt body gt module head goal where goal is not a variable module body body gt body body body gt body body body body body body goal term where term is not otherwise a body gr head gt gr body gt module gr head gr head terminals non terminal i where non terminal is not a variable Y module gr body gr body gt gr body gr body gr body gt gr body gr
454. re made for the selected variable X step Makes a binary choice between X B and X B where B is the lower or upper bound of X This is the default enum Makes a multiple choice for X corresponding to the values in its domain bisect Makes a binary choice between X lt M and X gt M where M is the midpoint of the domain of X This strategy is also known as domain split ting The following options control the order in which the choices are made for the selected variable X up The domain is explored in ascending order This is the default down The domain is explored in descending order The following options control whether all solutions should be enumerated by back tracking or whether a single solution that minimizes maximizes X is returned if one exists all All solutions are enumerated This is the default minimize X maximize X Uses a branch and bound algorithm to find an assignment that minimizes maximizes the domain variable X The labeling should constrain X to become assigned for all assignments of Variables Finally the following option counts the number of assumptions choices made during the search statistics K When a solution is found K is unified with the number of choices made For example to enumerate solutions using a static variable ordering use constraints Variables labeling Variables same as leftmost step up all To minimize a cost function using branch an
455. re to be read for each a a is true and for each a a is false respectively and so T 0 in both cases since both are unsatisfiable This illustrates the fact that the implicit universal quantifiers introduced by symbolic constants are placed in front of the entire expression 28 2 3 Example 3 user adder X Y Sum Cin Cout sat Sum card 1 3 X Y CinJ sat Cout card 2 3 X Y Cin user consulted 40 msec 576 bytes yes adder x y Sum cin Cout sat Sum cin x y sat Cout x cin x xy y cin yes adder x y Sum 0 Cout sat Sum x y sat Cout x y yes 244 SICStus Prolog adder X Y 0 Cin 1 labeling X Y Cin Cin 0 X 1 Y 217 7 Cin 1 X 0 Y 217 7 Cin 1 X 1 Y 07 illustrates the use of cardinality constraints and models a one bit adder circuit The first query illustrates how representing the input signals by symbolic constants forces the output signals to be displayed as functions of the inputs and not vice versa The second query computes the simplified functions obtained by setting carry in to 0 The third query asks for particular input values satisfying sum and carry out being 0 and 1 respectively 28 2 4 Example 4 The predicate fault 3 below describes a 1 bit adder consisting of five gates with at most one faulty gate If one of the variables Fi is equal to 1 the corresponding gate is faulty and its ou
456. ream is referenced by user_output and SP_stdout It is initially set to a stream connected to UNIX stdout user_error Permitted values are any stream opened for writing Controls which stream is referenced by user_error and SP_stderr It is initially set to a stream connected to UNIX stderr version A read only flag The value is an atom containing the banner text dis played on startup and reinitialization such as SICStus 3 0 Wed Mar 15 12 29 29 MET 1995 toplevel_print_options The value is a list of options for write_term 3 see Section 7 1 3 Term I O page 80 to be used when the top level dis plays variable bindings answer constraints and uncaught excep tions Not available in Runtime Systems The initial value is quoted true numbervars true portrayed true max_depth 10 108 SICStus Prolog debugger_print_options The value is a list of options for write_term 3 see Section 7 1 3 Term I O page 80 to be used in the debugger s messages Not available in Runtime Systems The initial value is quoted true numbervars true portrayed true max_depth 10 source_info on or of f If on while code is being loaded information about line numbers and filenames are stored with the loaded code If on while debugging this information is used to display the source code location while prompting for a debugger command Initially off Currently this facility is only useful with the GNU Emacs interface pro
457. riable expression An expression evaluates to a number which may be an integer or a float The range of integers is 2 2147483616 272147483616 Thus for all practical purposes the range of integers can be considered infinite The range of floats is the one provided by the C double type typically 4 9e 324 1 8e 308 plus or minus Only certain functors are permitted in an arithmetic expression These are listed below together with an indication of the functions they represent X and Y are assumed to be arithmetic expres sions Unless stated otherwise the arguments of an expression may be any numbers and its value is a float if any of its arguments is a float otherwise the value is an integer Any implicit coercions are performed with the integer 1 and float 1 functions X The value is X X The value is the negative of X X Y The value is the sum of X and Y X Y The value is the difference of X and Y X Y The value is the product of X and Y X Y The value is the float quotient of X and Y X Y The value is the integer quotient of X and Y X mod Y The value is the integer remainder after dividing X by Y ie integer X integer Y X Y integer X The value is the closest integer between X and 0 if X is a float otherwise to X itself float X The value is the float equivalent of X if X is an integer otherwise to X itself X Y The value is the bitwise conjunction of the integers X and Y XN Y The value is t
458. rm 201 LD_LIBRARY_PATH environment 9 155 156 LD_RUN_PATH environment e sess 9 leap debugger command 0 0 eee eee 65 le sh l dd rad 62 121 Lenta indi 124 library directory 1 isse 90 LIBRARY_PATH environment ssssss 9 danda Orc ete atenta e e ita af rea re e e Rn 232 VIDA A A E quive qe odio deu 232 Iinda ckient l c d e Agi d aAA RA 233 linda timeout 2 ssseeeeeeee eee 233 lime count 2 Lc eR PHA REPE EL as 91 l1ine positi n 2 v0 be Bee ean daa 91 414 link foreign resource 6 0c eee eae 133 List queue 2 i cir e hive bene eden RES ERECPPACG tas 212 List to assoc 2 4i ERE Pp XO Edd AE 192 Iist toctdset 2 ib pM EET MERKUR 287 List to henp 2 eei tege m 199 List to ord set 2 2 o boi i por RE ERIS ER 207 Iist to tree 2 o ERES 219 Viste O io A tengas 104 at e ont hain rs d bared ds 104 LOAG 1h 1 piodin ee Red Ad eee BUA eet 53 74 Joad tiles druida 73 Toad files 2edre dp WIPE eee DARE TI ARR T3 load foreign files 2 iss sese 134 load foreign resource 1 cece eee 133 local stack statistics 2 option 109 LOCALSTKSIZE environment sess 10 log 1 logarithme Li e erede 96 log 2 logarithm 0c cece cece nee 96 M make directory i lue ep Ree thy wes d 215 make index make library index 1 188 nap assoc 2izi iicet ohh bn xv pr Patten wats 192 MAP
459. rm is uninstantiated then List must be instantiated either to a list of determinate length whose head is an atom or to a list of length 1 whose head is a number Note that this predicate is not strictly necessary since its functionality can be provided by arg 3 and functor 3 and using the latter two is usually more efficient name 4 Const CharList name Const CharList If Const is an atom or number CharList is a list of the character codes of the characters comprising the name of Const e g name product L L 112 114 111 100 117 99 116 name product product name 1976 L p li 49 57 55 54 112 SICStus Prolog name 1976 L L 49 57 55 54 name L L 58 45 If Const is uninstantiated CharList must be instantiated to a list of character codes If CharList can be interpreted as a number Const is unified with that number otherwise with the atom whose name is CharList E g name X 58 45 X name X name X 49 50 51 X 123 Note that there atoms are for which name Const CharList is true but which will not be constructed if name 2 is called with Const uninstantiated One such atom is the atom 1976 It is recommended that new programs use atom_chars 2 or number chars 2 as these predicates do not have this inconsistency atom chars Const CharList ISO atom chars Const CharList ISO The same a
460. rn CR 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 Chapter 31 Constraint Handling Rules 321 lt CR gt CHR debugging options lt cr gt creep c creep 1 leap S Skip S lt i gt skip ancestor i E ancestors amp constraints amp lt i gt constraints details n nodebug debugging spy this nospy this E show rule lt reset printdepth lt lt n gt set printdepth a abort b break help h help creep causes the debugger to single step to the very next port and print a message 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 running 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
461. rolog 3 look for a feasible solution via backtrack search or look for an optimal solution via branch and bound search Sometimes an extra step precedes the search for a solution the posting of surrogate constraints to break symmetries or to otherwise help prune the search space No surrogate constraints are used in this example The domains of this puzzle are stated via the domain 3 goal and by requiring that S and M be greater than zero The two problem constraint of this puzzle are the equation sum 8 and the constraint that all letters take distinct values all_different 1 Finally the backtrack search is performed by labeling 2 Different search strategies can be encoded in the Type parameter In the example query the default search strategy is used select the leftmost variable try values in ascending order use_module library clpfd mm S E N D M O R Y Type domain S E N D M O R Y 0 9 step 1 S gt 0 M gt 0 all_different S E N D M 0 R Y step 2 sum S E N D M 0 R Y labeling Type S E N D M 0 R Y step 3 sum S E N D M O R Y 1000 S 100 E 10 N D 1000 M 100 0 10 R E 10000 M 1000 0 100 N 10 E Y mm S E N D M O R Y D 7 E 5 M 1 N 6 0 0 R 8 S 9 Y 2 30 2 3 Reified Constraints Instead of merely posting constraints it is often useful to reflect its truth value into a 0 1 variable B so that e the constraint is posted
462. s Since this might get confusing each invocation box is given a unique integer identifier 6 2 Basic Debugging Predicates Development Systems provide a range of built in predicates for control of the debugging facilities The most basic predicates are as follows debug Switches the debugger on and ensures that the next time control reaches a spy point a message will be produced and you will be prompted for a command In order for the full range of control flow information to be available it is necessary to have this on from the start When it is off the system does not remember invocations that are being executed This is because it is expensive and not required for normal running of programs You can switch Debug Mode on in the middle of execution either from within your program or after a C see trace 0 below but information prior to this will just be unavailable zip Same as debug 0 except no debugging information is being collected and so is almost as fast as running with the debugger switched off trace Switches the debugger on and ensures that the next time control enters an invocation box a message will be produced and you will be prompted for a command The effect of trace can also be achieved by typing t after a C interruption of a program At this point you have a number of options See Section 6 5 Debug Options page 65 In particular you can just type RET to creep or single step into your program If you continue
463. s Term1 and Term2 This process is sometimes called anti unification as it is the dual of unification term subsumer f g 1 h f g _ h 1 T T f gC B hC A term subsumer f 142 241 3 4 4 3 T T f _A _B _B _A 206 SICStus Prolog term_hash Term Hash term_hash Term Depth Range Hash If Term is instantiated up to the given Depth an integer hash value in the range 0 Range as a function of Term is unified with Hash Otherwise the goal just succeeds leaving Hash uninstantiated If Term contains floats or integers outside the range 33554432 33554431 the hash value will be platform dependent Otherwise the hash value will be identical across runs and platforms The depth of a term is defined as follows the principal functor of the term itself has depth 1 and an argument of a term with depth i has depth i 1 Depth should be an integer 1 If Depth 1 the default Term must be ground and all subterms of Term are relevant in computing Hash Otherwise only the subterms up to depth Depth of Term are used in the computation Range should be an integer gt 1 The default will give hash values in a range appro priate for all platforms term hash a b 3 4 HB H 2 term_hash a b _ 4 4 H true term_hash f a f b f _ 01 2 4 H H 2 term hash 2 4 is provided primarily as a tool for the construction of sophisticated Prolog clause access sc
464. s allocated Chapter 7 Built In Predicates 109 local_stack trail choice core memory heap program runtime walltime size used free This refers to the local stack where recursive predicate environments are stored size used free This refers to the trail stack where conditional variable bindings are recorded size used free This refers to the choicepoint stack where partial states are stored for backtracking purposes size used 0 These refer to the amount of memory actually allocated by the process size used 0 These refer to the amount of memory allocated for compiled and interpreted clauses symbol tables and the like since start of Prolog since previous statistics These refer to CPU time used while executing excluding time spent garbage collecting stack shift ing or in system calls In Muse these numbers refer to the worker that happens to be executing the call to statistics 2 and so normally are not meaningful since start of Prolog since previous statistics These refer to absolute time elapsed garbage_collection no of GCs bytes freed time spent stack_shifts atoms no of local shifts no of trail shifts time spent no of atoms bytes used bytes free atom_garbage_collection no of AGCs bytes freed time spent Times are in milliseconds sizes of areas in bytes 110 SICStus Prolog 7 7 Meta Logic The predicates in this section are m
465. s and runtime systems have been reorganized around a common runtime kernel This kernel is delivered as a shared object DLL which means that the runtime linker must be able to locate it at runtime Under Windows the runtime linker usually has no problem locating the correct DLLs The rest of this section is therefore Unix specific Most Unix systems rely partly on the so called runtime linker search path which tells the runtime linker where it should look for shared objects in addition to the default paths such as 1ib usr lib usr local lib and so on SICStus start script fixes this by setting the runtime linker search path variable together with SP_ PATH See Section 1 1 2 Environment Variables page 10 to their correct values There is also a flag base to the start script which forces it to use a different executable This is very useful when bulding statically linked Development Systems see Section 8 9 Development Systems page 156 By using the base flag the start script can be used also for these For example to execute a statically linked Development System called myapp sicstus base myapp However this is only possible to do with Development Systems Runtime Systems cannot be started using the SICStus start script and therefore may have to set the runtime linker search path variable explicitly The following is how a typical error looks like when the runtime linker cannot find the SICStus runtime kernel
466. s any goals that have exited non deterministically and their ancestors This information shows where there are outstanding choices that the program could backtrack to If you supply an integer n then only that number of goals will be printed Ancestors to the current goal are annotated with the Call port as they have not yet exited whereas goals that have exited are annotated with the Exit port The backtrace is a tree rather than a stack to find the parent of a given goal with depth indicator d look for the closest goal above it with depth indicator d 1 print blocked goals prints a list of the goals which are currently blocked in the current debugging session together with the variable that each such goal is blocked on see Section 2 3 Procedural page 34 The goals are enumerated from 1 and up If you supply an integer n then only that goal will be printed Each entry is preceded by the goal number followed by the variable name nodebug switches the debugger off Note that this is the correct way to switch debug ging off at a trace point You cannot use the or b options because they always return to the debugger debugging outputs information concerning the status of the debugging package See Section 7 14 Debug Pred page 120 the built in debugging O spy this sets a spy point on the current goal With an argument prompts for a condition to be tested each time the debugger reaches the spy point Conditions consist
467. s are also allowed in a prefixed form using as a prefix A method directive is a directive which contains method calls All sentences are subject to term expansion see Section 7 1 2 Definite page 76 built in expand_ term 2 before further processing so in particular definite clause grammar syntax can be used in method clauses In addition before expand_term 2 sentences are expanded by the predicate user method_expansion 3 Chapter 32 Prolog Objects 329 method expansion Terml ObjectIdentifier Term2 user method_expansion Term ObjectIdentifier Term2 A hook predicate which defines transformations on methods similarly as user term_ expansion 2 4 At the end of an object definition user method_expansion 3 is called with end_of_object 32 2 2 Method Declarations Method clauses are declared similarly to Prolog clauses Thus a method clause can be either a unit clause or a non unit clause We also allow a default catch all method clause as the last clause in an object body The catch all clause has as its head a Prolog variable in order to match messages that are not previously defined or inherited in the object It can be used to implement alternative inheritance mechanisms Goals in the body of a non unit clause have the normal control structures of Prolog P Q Conjunction P Q Disjunction Cut P Negation P gt Q P gt Q R if CP Q R If then else A B Unification
468. s called Dynamic linking is not possible if the foreign resource was linked using the static option If a resource with the same name has been previously loaded it will be unloaded as if unload foreign resource Resource was called before Resource is loaded In Muse the system is required to be adjusted to one worker first and the predicates defined become cavalier see Section 3 5 Programming Considerations page 45 unload foreign resource Resource Any deinit function associated with Resource is called and the predicates defined by Resource are uninstalled If Resource has been dynamically linked it is unlinked from the Prolog load image 134 SICStus Prolog In Muse the system is required to be adjusted to one worker first and the predicates defined become cavalier The following predicates are provided for backwards compatibility and should be avoided in new code foreign_file File Functions A hook predicate Specifies that a set of foreign functions to be called from Prolog are to be found in File This predicate is only called from load_foreign_files 2 load foreign files ObjectFiles Libraries Hookable a resource name is derived from the first file name in ObjectFiles by stripping off the suffix If this resource has been statically linked the predicates defined by it are installed otherwise a linked foreign resource containing the declared functions is created and loaded Not available in Runtime Sys
469. s converted to a C long and passed to the C function Prolog float C double The argument should be a number It is converted to a C double and passed to the C function Prolog atom C unsigned long The argument should be an atom Its canonical representation is passed to the C function Prolog chars C char The argument should be a list of character codes The C function will be passed the address of an array of characters containing these characters The array is subject to reuse by other support functions so if the value is going to be used on a more than temporary basis it must be moved elsewhere Prolog string C char The argument should be an atom The C function will be passed the address of a text string containing the printed representation of the atom The C function should not overwrite the string Prolog string N C char The argument should be an atom The printable representation of the string will be copied into a newly allocated buffer The string will be truncated if it is longer than N characters The string will be blank padded on the right if it is shorter than N characters The C function will be passed the address of the buffer The C function may overwrite the buffer but should not assume that it remains valid after returning Prolog address C void The argument should be an integer which value is constrained according to see Sec tion 8 3 2 Creating Prolog Terms page 137 SP put
470. s in SICStus Prolog One set is inherited from DEC 10 Prolog These predicates always refer to a file by name The other set of predicates is modeled after Quintus Prolog and refer to files as streams Streams correspond to the file pointers used at the operating system level A stream can be opened and connected to a filename or file descriptor for input or output by calling the predicate open 3 open 3 will return a reference to a stream The stream may then be passed as an argument to various I O predicates The predicate close 1 is used for closing a stream The predicate current stream 3 is used for retrieving information about a stream and for finding the currently existing streams 72 SICStus Prolog Prolog streams can be accessed from C functions as well See Section 8 5 SICStus Streams page 144 for details The possible formats of a stream are stream X A stream connected to some file X is an integer user_input An alias initially referring to the UNIX stdin stream The alias can be changed with prolog_flag 3 and accessed by the C variable SP_stdin user_output An alias initially referring to the UNIX stdout stream The alias can be changed with prolog_flag 3 and accessed by the C variable SP_stdout user_error An alias initially referring to the UNIX stderr stream The alias can be changed with prolog_flag 3 and accessed by the C variable SP_stderr This stream is used by the Prolog top level and debugger and for
471. s name Const CharList but Const is constrained to be an atom This predicate is called atom codes 2 in the ISO Prolog standard number chars 4 Const CharList ISO number chars Const CharList ISO The same as name Const CharList but Const is constrained to be a number This predicate is called number codes 2 in the ISO Prolog standard copy term Term CopyOfTerm ISO CopyOfTerm is a renaming of Term such that brand new variables have been substi tuted for all variables in Term If any of the variables of Term have goals blocked on them the copied variables will have copies of the goals blocked on them as well Simi larly independent copies are substituted for any mutable terms in term It behaves as if defined by copy_term X Y assert copy of Q0 retract copy of Y The implementation of copy_term 2 conserves space by not copying ground subterms Chapter 7 Built In Predicates 113 7 8 Modification of Terms One of the tenets of logic programming is that terms are immutable objects of the Herbrand universe and the only sense in which they can be modified is by means of instantiating non ground parts There are however algorithms where destructive assignment is essential for performance Although alien to the ideals of logic programming this feature can be defended on practical grounds SICStus Prolog provides an abstract datatype and three operations for efficient backtrackabl
472. s name Chars is unified with the list alternatively S0 and S are unified with the head and tail of the list respectively read from chars Chars Term Reads Term from Chars using read 2 The Chars must as usual be terminated by a full stop i e a possibly followed by layout text open chars stream Chars Stream Stream is opened as an input stream to an existing list of character codes T he stream may be read with the Stream I O predicates and must be closed using close 1 The list is copied to an internal buffer when the stream is opened and must therefore be a ground list of character codes at that point with output to chars Goal Chars with output to chars Goal S0 S 370 SICStus Prolog with_output_to_chars Goal Stream 50 S Goal is called with the current_output stream set to a new stream This stream writes to an internal buffer which is after the successful execution of Goal converted to a list of character codes Chars is unified with the list alternatively SO and S are unified with the head and tail of the list respectively with_output_to_chars 4 also passes the stream in the Stream argument It can be used only by Goal for writing Chapter 37 Jasper 371 37 Jasper The Jasper library module provides functionality for accessing the Java VM from Prolog The current functionality is limited to calling methods using the standard foreign language interface See Chapter 9 Mixing Java and Pr
473. se D X S contains some values that are known to be incompatible with C Hence X S R is added to the store X is pruned and the indexical suspends unless R is ground in S in which case C is detected as entailed A propagating indexical is scheduled for execution as follows e it is evaluated initially as soon as it has become monotone e it is re evaluated when one of the following conditions occurs 1 the domain of a variable Y that occurs as dom Y or card Y in R has been updated 2 the lower bound of a variable Y that occurs as min Y in R has been updated 3 the upper bound of a variable Y that occurs as max CY in R has been updated 30 9 7 Execution of Checking Indexicals Consider the definition of a constraint C containing a checking indexical X in R Let FV X C S denote the set of values for X that can make C false in some ground extension of the store S Then the indexical should obey the following coding rules e all arguments of C except X should occur in R e if R is ground in S S R TV X C S If the coding rules are observed S R can be proven to exclude FV X C 5 for all stores in which R is anti monotone Hence it is natural for the implementation to wait until R becomes anti monotone before admitting the checking indexical for execution The execution of X in R thus involves the following e If D X S is contained in S R none of the possible values for X can make C false and so C is detected as entailed C
474. set stream Stream Curr ut reset stream Stream CurrQut set output Curr ut close Stream The C code include lt sicstus sicstus h gt struct open_chars char chars character buffer int index current insertion point Chapter 8 Mixing C and Prolog 161 int size define INIT_BUFSIZE 512 static int lputc c buf int c struct open_chars buf if buf gt index buf gt size grow buffer if necessary buf gt size 2 buf gt chars char realloc buf gt chars buf gt size return buf gt chars buf gt index c static int lwclose buf struct open_chars buf t free buf gt chars free buf return 0 void open_buf_stream streamp SP_stream streamp struct open_chars buf Allocate buffer create stream amp return stream code buf struct open_chars malloc sizeof struct open_chars SP_make_stream buf NULL lputc NULL NULL NULL lwclose streamp buf gt chars char malloc INIT_BUFSIZE buf gt size INIT_BUFSIZE buf gt index 0 i void stream to chars streamp head SP stream streamp SP term ref head SP_term_ref tail SP_new_term_ref struct open_chars buf struct open_chars streamp gt user_handle 162 SICStus Prolog Make a list of character codes out of the buffer SP_put_string tail SP_put_list_chars head tail buf gt chars 8 10 3 Exceptions from C
475. sists of one or more hidden modules An alternative way of loading from the library is using the built in predicate require 1 see Section 7 1 1 Read In page 73 The index file INDEX p1 needed by require 1 can be created by the make index program This program is loaded as use module library mkindex make index make library index 4 LibraryDirectory Creates a file INDEX pl in LibraryDirectory All p1 files in the directory and all its subdirectories are scanned for module 2 declarations From these declarations the exported predicates are entered into the index Chapter 12 Array Operations 189 12 Array Operations This package provides an implementation of extendible arrays with logarithmic access time Beware the atom is used to indicate an unset element and the functor 4 is used to indicate a subtree In general array elements whose principal function symbol is will not work To load the package enter the query use module library arrays new array Array Binds Array to a new empty array Example new array A A array 2 yes is array Array Is true when Array actually is an array aref Index Array Element Element is the element at position Index in Array It fails if Array Index is undefined arefa Index Array Element Is like aref 3 except that Element is a new array if Array Index is undefined Ex ample arefa
476. so in standard order as produced by sort every neighbor appears as a vertex even if it has no neighbors itself and no vertex is a neighbor to itself An undirected graph is represented as a directed graph where for each edge U V there is a symmetric edge V U An edge U V is represented as the term U V U and V must be distinct A vertex can be any term Two vertices are distinct iff they are not identical A path from u to v is represented as a list of vertices beginning with u and ending with v A vertex cannot appear twice in a path A path is maximal in a graph if it cannot be extended A tree is a tree shaped directed graph all vertices have a single predecessor except the root node which has none A strongly connected component of a graph is a maximal set of vertices where each vertex has a path in the graph to every other vertex Sets are represented as ordered lists see Chapter 18 Ordsets page 207 To load the package enter the query use module library ugraphs The following predicates are defined for directed graphs vertices edges to ugraph Vertices Edges Graph Is true if Vertices is a list of vertices Edges is a list of edges and Graph is a graph built from Vertices and Edges Vertices and Edges may be in any order The vertices mentioned in Edges do not have to occur explicitly in Vertices Vertices may be used to specify vertices that are not connected by any edges vertices Graph
477. some of the elements of List in the same order substitute X Xlist Y Ylist Xlist and Ylist are equal except for replacing identical occurrences of X by Y Example substitute 1 1 2 3 4 5 X X 5 2 3 4 yes sum list ListOfNumbers Sum Sum is the result of adding the ListOfNumbers together suffix Suffix List Suffix is a suffix of List 204 SICStus Prolog Chapter 17 Term Utilities 205 17 Term Utilities This package defines operations on terms for subsumption checking anti unification unification with occurs check testing acyclicity and getting the variables To load the package enter the query use module library terms subsumes chk General Specific Specific is an instance of General i e if there is a substitution that leaves Specific unchanged and makes General identical to Specific It doesn t bind any variables subsumes chk X f a true subsumes chk f a X no subsumes chk A A B C no subsumes chk A B C C true subsumes General Specific Specific is an instance of General It will bind variables in General but not those in Specific so that General becomes identical to Specific variant Term Variant Term and Variant are identical modulo renaming of variables provided Term and Variant have no variables in common term subsumer Terml Term2 General General is the most specific term that generalize
478. spect to X is 1 The goal of finding a derivative for the expression X with respect to X itself is satisfied by the result 1 3 ungulate X aquatic X Is it true for any X that X is an ungulate and X is aquatic Find an X which is both an ungulate and aquatic In any program the predicate for a particular principal functor is the sequence of clauses in the program whose head goals have that principal functor For example the predicate for a 3 ary functor concatenate 3 might well consist of the two clauses concatenate L L concatenate X L1 L2 XIL3 concatenate Li L2 L3 where concatenate L1 L2 L3 means the list L1 concatenated with the list L2 is the list L3 Note that for predicates with clauses corresponding to a base case and a recursive case the preferred style is to write the base case clause first In Prolog several predicates may have the same name but different arities T herefore when it is important to specify a predicate unambiguously the form name arity is used e g concatenate 3 Certain predicates are predefined by built in predicates supplied by the Prolog system Such pred icates are called built in predicates As we have seen the goals in the body of a sentence are linked by the operator which can be interpreted as conjunction and It is sometimes convenient to use an additional operator 6 standing for disjunction or The prec
479. st The current subterm is set to the current goal when arriving at a new port This command without arguments resets the current subterm to the current goal With an argument of n gt 0 the current subterm is replaced by its n th subterm With an argument of 0 the current subterm is replaced by its parent term With a list of arguments the arguments are applied from left to right help displays the table of options given above 6 6 Consulting during Debugging It is possible and sometimes useful to consult a file whilst in the middle of program execution Predicates which have been successfully executed and are subsequently redefined by a consult and are later reactivated by backtracking will not notice the change of their definitions In other words it is as if every predicate when called creates a virtual copy of its definition for backtracking purposes If SICStus Prolog is run via the Emacs interface the commands for loading code such as C c C p consulting the current predicate are not directly available when the system prompts you after Chapter 6 Debugging 69 printing out a debugging message Press b followed by RET to get a recursive top level ready to accept the Emacs commands Type D to return to the debugging port 6 7 Catching Exceptions Usually exceptions that occur during debugging sessions are displayed only in trace mode and for invocation boxes for predicates with spy points on them and not during sk
480. st load the jasper module and thereby the JVM and then load the simple foreign resource which defines the simple 2 predicate 9 4 Calling Prolog from Java Calling Prolog from Java is done by using the Java package jasper This package contains a set of Java classes which can be used to create and manipulate terms ask queries and request one or more solutions The functionality provided by this set of classes is basically the same as the functionality provided by the C Prolog interface see Chapter 8 Mixing C and Prolog page 127 The usage is easiest described by an example The following is a Java version of the train example See Section 8 10 1 Train page 157 import jasper public class Simple 1 public static void main String argv 1 SICStus sp SPPredicate pred SPTerm from to way SPQuery query int i 174 SICStus Prolog try sp new SICStus argv null sp load train ql pred new SPPredicate sp connected 4 to new SPTerm sp Orebro from new SPTerm sp Stockholm way new SPTerm sp putVariable query sp openQuery pred new SPTerm from to way way 3 while query nextSolution System out println way toStringO catch Exception e e printStackTrace This is how it works 1 First we import all the jasper classes To find them the class path should be set to contain the path to the SICStus libraries SP_PATH library How
481. st of those terms without duplicates in the standard order for terms see Section 7 3 Term Compare page 97 If there are no instances of Template such that Goal is satisfied then the predicate fails The variables appearing in the term Template should not appear anywhere else in the clause except within the term Goal Obviously the set to be enumerated should be finite and should be enumerable by Prolog in finite time It is possible for the provable instances to contain variables but in this case the list Set will only provide an imperfect representation of what is in reality an infinite set If there are uninstantiated variables in Goal which do not also appear in Template then a call to this built in predicate may backtrack generating alternative values for Set corresponding to different instantiations of the free variables of Goal It is to cater for such usage that the set Set is constrained to be non empty Two instantiations are different iff no renaming of variables can make them literally identical For example given the clauses likes bill cider likes dick beer likes harry beer likes jan cider likes tom beer likes tom cider the query setof X likes X Y S might produce two alternative solutions via backtracking S dick harry tom Y beer S bill jan tom Y cider The query setof Y S setof X likes X Y S SS would then produce SS beer dick harry t
482. stance Instance set x IX 302 SICStus Prolog Instance set y IY amp location X Y lt xy X Y amp move horizontal X set x X amp move vertical Y set y Y amp move X Y lt move horizontal X lt move vertical Y amp display Terminal lt xy X Y Terminal format point at d d n X Y history_point super point 4 attributes history new Instance xy IX IY super lt new Instance xy IX IY Instance set history IX IY amp move X Y super move X Y get history History set history X Y History display Terminal super lt display Terminal lt print history Terminal amp print history Terminal get history History Terminal format with location history w n History bounded_point super point amp attributes bounds 0 0 0 0 amp Chapter 32 Prolog Objects 303 new Instance Coords Bounds super lt new Instance Coords Instance set_bounds Bounds set Bounds amp move X Y set_bounds Bounds amp lt bound_constraint X Y super lt move X Y amp move _ _ amp bound constraint X Y get bounds XO X1 YO Y1 X gt X0 SX lt X1 Y gt YO Y lt Y1 amp display Terminal super lt display Terminal lt print_bounds Terminal am
483. stance 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 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 A 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 checked 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 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 no
484. stant ConstantRange Constant Range ConstantRange Constant Range Constant Range MapList integer ConstantRange MapList CList integer CList pointwise modulo Chapter 30 Constraint Logic Programming over Finite Domains 303 Indexical gt X in Range Indexicals gt Indexical Indexical Indexicals ConstraintBody gt Indexicals LinExpr RelOp LinExpr element X CList X relation X MapList X Head gt term compound term with unique variable args TellPos Head ConstraintBody TellNeg Head ConstraintBody AskPos Head Indexical AskNeg Head Indexical ConstraintDef TellPos TellNeg AskPos AskNeg Syntax of Arithmetic Expressions X variable domain variable N gt integer LinExpr gt N linear expression X Nx X Nx WN LinExpr LinExpr LinExpr LinExpr Expr LinExpr Expr Expr Expr Expr Expr Expr Expr Expr 1 integer division Expr mod Expr min Expr Expr max Expr Expr abs Expr RelOp lt lt gt gt 304 Operator Declarations op 1200 op 760 op 750 op 750 op 740 op 730 op 720 op 710 op 700 op 700 op 550 op 500 op 490 op 400 xfx yfx xfy yfx yfx yfx yfx fy xfx xfx xfx fy yfx yfx lt gt
485. statically linked in which case only the binding of predicate names to functions needs to be done Otherwise dynamic linking is attempted With dynamic linking the linked foreign resource can be linked and unlinked to a Development or Runtime System as needed A linked foreign resource may be implemented depending on the hardware and operating system platform as e g a shared object or a dynamic link library 8 2 3 Conversion Declarations Conversion declaration predicates foreign resource ResourceName Functions A hook predicate Specifies that a set of foreign functions to be called from Prolog are to be found in the resource named by ResourceName Functions is a list of func tions exported by the resource Only functions that are to be called from Prolog and optionally one init function and one deinit function should be listed The init and deinit functions are specified as init Function and deinit Function respectively see Section 8 2 6 Init and Deinit Functions page 134 This predicate should be defined entirely in terms of facts unit clauses For example foreign resource terminal scroll pos_cursor ask specifies that functions scroll pos_cursor and ask are to be found in the resource terminal foreign CFunctionName Predicate foreign CFunctionName Language Predicate Hook predicates specify the Prolog interface to a C function Language is at present constrained to the atom c
486. sts data junk If a command like this were contained in the file myprog then typing the following at top level would be a quick way of reading in your entire program myprog When simply interacting with the top level this distinction between queries and commands is not normally very important At top level you should just type queries normally In a file queries are in fact treated as commands i e if you wish to execute some goals then the directive in the file must be preceded by or otherwise it would be treated as a clause 1 5 Syntax Errors Syntax errors are detected during reading Each clause directive or in general any term read in by the built in predicate read 1 that fails to comply with syntax requirements is displayed on the standard error stream as soon as it is read along with its position in the input stream and a mark indicating the point in the string of symbols where the parser has failed to continue analysis e g member X X L SYNTAX ERROR in line 5 within 5 6 or expected in arguments member X X here L if has not been declared as an infix operator Note that any comments in the faulty line are not displayed with the error message If you are in doubt about which clause was wrong you can use the listing 1 predicate to list all the clauses which were successfully read in e g Chapter 1 How to Run Prolog 15 listing member 2 Note
487. stus keys flag 23 prolog paren indent 0 cece eee eee 22 prolog parse mode 6 cece ccc eee 23 Prolog system sss eee eee 22 prolog system version 0 cece eee ee eee 22 prolog underscore wordchar lag 24 prolog use prolog tokenizer flag 23 prolog use Sicstus Sd eee eee 22 R restart 0 utility method 44 344 retract 1 object method sss 343 retractall 1 object method 343 S self 1 inlined method 0005 341 self 1 object method 342 set 1 inlined method 000 0 341 set 1 object method 0 cece eee eee 342 static 0 object method 00005 342 static 1 object method o ooooooooomoooo 342 static_methods 1 utility method 344 422 static objects 1 utility method 344 SUD Diarra es rk aoe a uen tibeie dag du 342 sub 1 object method 0 cece eee eee 335 subs 1 utility method 006 343 super keyword ociera 0 ccc e cece eee 336 SUPE Liria eee rs MUS iur cti orae 342 SICStus Prolog super 2 universal method 334 341 supers 1 utility method 0 343 update 1 object method oooooooomoomo o 343 utility built in object o ooooo ocoomoo 343 Concept Index Concept Index ADO A DUE Miah be
488. su 140 SP new term ref C function 136 SP next solution C function 142 SP on fault C macro 0 0 0005 153 SP open query C function 142 SP_PATH environment suus 10 127 SP pred C function 004 141 SP predicate C function ssssusn 141 SP printf C function sssussss 145 SP put address C function 137 SP put atom C function ssss 137 SP put float C function 137 SP put functor C function 137 SP put integer C function 137 SP put list C function ssss 137 SP put list chars C function 137 417 SP_put_list_n_chars C function 137 SP_put_number_chars C function 137 SP_put_string C function 137 SP put term C function 00 136 SP_put_variable C function 137 SP putc C function 0 004 145 SP_puts C function 008 145 SP qid C type sende d eda ess vun P dat 142 SP query C function sssssssss 141 SP query cut fail C function 141 SP raise exception C function 144 SP raise fault C function 154 SP realloc C function
489. t esie er E a 74 TECLA Vic Ao 116 HO COPdEd Buin ii tab rm Sahara TS 116 Te COLdZ Bidets ue ive eR e abis ues 116 redefine warnings prolog flag 106 reduce 2 s vossp EUG UE PECIF RU Dee 222 226 reinitiallse 0 ona ERE E etenia s 125 rel amp tion 3 inet wis s vein ohne equas 277 remove constraint 1 esses eee eee 314 remove duplicates 2 cies 203 rename file 2 ib y Wok adios reese Erud 217 TOPE Diari edet aaa Ted bea d 100 representation error 3 error class 103 require l viec Cu oeste eem a beg dads 75 reset printdepth debugger command 68 reset subterm debugger command 68 r8store laelL ers UR REMUBEMPEP Pe pb eps 17 125 petr ct lno il s ee RP ae os ULP PE TA EROR 114 retractall 1 ig bb and YAN 115 retry debugger command esses 66 TOTES AZ rl tate Red Lbs Yao doe 203 round 1 function ccc cece cece eee eee 95 runtime statistics 2 option 109 S same length 2 Rua c ep E Eb El 203 same length 3 ocv reri Eve TL Qr bene eee ees 203 Sat d nocuit spat e e META TRIP IE 242 save program 1 ope Uebel pese NE ES 17 125 save program 2 isse nne 17 125 scalar product 4 omic tanec e ed P eR 276 CITATI 93 Seeing l uk sere UEA nnne de ewe dod 93 Seek 4 ouo A ret dist 91 Seen Q c itio tis eek AAA was eta 93 SOLOCE Sista ae e VS MORE LU RO ERR 203 sequential O declaration 00
490. t gt w_stream int socket_seof SocketData socket return feof socket gt r_stream void socket_sclrerr SocketData socket clearerr socket gt r_stream clearerr socket gt w_stream int socket_sclose SocketData socket fclose socket gt r_stream fclose socket gt w_stream close socket gt fd free socket return 0 Chapter 8 Mixing C and Prolog 165 SP_stream new_socket_stream int fd E SP_stream stream SocketData socket Allocate and initialize data local to socket socket SocketData malloc sizeof SocketData socket gt fd fd socket gt r_stream fdopen fd r Socket w stream fdopen fd w Allocate and initialize Prolog stream SP_make_stream socket socket_sgetc socket_sputc socket_sflush socket_seof socket_sclrerr socket_sclose amp stream Allocate and copy string stream gt filename socket stream gt fd fd return stream 166 SICStus Prolog Chapter 9 Mixing Java and Prolog 167 9 Mixing Java and Prolog Jasper is a bi directional interface between programs written in Java and programs written in Prolog The Java side of the interface constists of a Java package jasper containing classes representing the SICStus emulator The Prolog part is designed as an extension to the foreign language interface which means that foreign 3 declarations are used to map Java methods on Prolog predicates
491. t a stream argument operate on the current input or output stream depending on context Some of these predicates support a notation for terms containing multiple occurrences of the same subterm cycles and DAGs The notation is Template Substitution where Substitution is a list of Var Term pairs where the Var occurs in Template or in one of the Terms This notation stands for the instance of Template obtained by binding each Var to its corresponding Term The purpose of this notation is to provide a finite printed representation of cyclic terms This notation is not used by default and 0 2 has no special meaning except in this context read Term ISO read Stream Term ISO The next term delimited by a full stop i e a possibly followed by layout text is read from Stream and is unified with Term The syntax of the term must agree with current operator declarations If a call read Stream Term causes the end of Stream to be reached Term is unified with the term end of file Further calls to read 2 Chapter 7 Built In Predicates 81 for the same stream will then raise an exception unless the stream is connected to the terminal read_term Term Options ISO read_term Stream Term Options ISO Same as read 1 2 with a list of options to provide extra control or information about the term Options is a list of zero or more of syntax errors Val Controls what action to take on syntax errors Val must be on
492. t and under Windows it is stored in the repository However under some circumstances it is necessary to set this variable explicitly for example when executing Runtime System which do not specify a path in the third argument to SP_initialize If set indicates the pathname where temporary files should be created Defaults to usr tmp GLOBALSTKSIZE Governs the initial size of the global stack LOCALSTKSIZE Governs the initial size of the local stack CHOICESTKSIZE Governs the initial size of the choicepoint stack TRAILSTKSIZE Governs the initial size of the trail stack PROLOGINITSIZE Governs the size of Prolog s initial memory allocation PROLOGMAXSIZE Defines a limit on the amount of data space which Prolog will use PROLOGINCSIZE Governs the amount of space Prolog asks the operating system for in any given memory expansion PROLOGKEEPSIZE Governs the size of space Prolog retains after performing some computation By default Prolog gets memory from the operating system as the user program executes and returns all free memory back to the operating system when the user program does not need any more If the programmer knows that her program once it has grown to a certain size is likely to need as much memory for future computations then she can advise Prolog not to return all the free memory back to the operating system by setting this variable Only memory that is allocated above and beyond PROLO
493. t 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 Chapter 31 Constraint Handling Rules 311 31 3 5 Pragmas Pragmas are annotations to rules and constraints that enable the compiler to generate more specific more optimized code A 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 removed by the rule This removal followed by addition is inefficient and may even cause termination problems If 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 p
494. t 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 LISP and some means to put syntactical terms back to their interpreted life 1 In a quote eval language meta programming is pragmatically simpler because everything is im plicitly quoted until explicitly evaluated On the other hand now object programming 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 266 SICStus Prolog clp r 242 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 2 0 2 0 X The same mechanism applies when interpreted terms are nested deeper some predicate 10 f A B 2 2 cos A Expands into Xc 2 0 cos A Xb A B 2 Xa 10 0 some predicate Xa f Xb Xc This process also applies when files are consulted or compile
495. t the Fail port it has no effect It transfers control to the Fail port of the box forcing the invocation to fail prematurely If you supply an integer after the command then this is taken as specifying an invoca tion number and the system tries to get you to the Fail port of the invocation box you have specified It does this by continuously failing until it reaches the right place Un fortunately this process cannot be guaranteed it may be the case that the invocation you are looking for has been cut out of the search space by cuts in your program In this case the system fails to the latest surviving Fail port before the correct one display goal displays the current goal using display 1 See Write below print goal re prints the current goal An argument will override the default printdepth treating 0 as infinity Chapter 6 Debugging 67 write goal writes the current goal using write 1 print ancestor goals provides you with a list of ancestors to the current goal i e all goals that are hierarchically above the current goal in the calling sequence You can always be sure of jumping to any goal in the ancestor list by using retry etc If you supply an integer n then only that number of ancestors will be printed That is to say the last n ancestors will be printed counting back from the current goal Each entry is displayed just as they would be in a trace message print backtrace is the same as the above but also show
496. t to user_input tel1 File The file File becomes the current output stream File may be a stream previously opened by tell 1 or a filename If it is a filename the following action is taken If there is a stream opened by tel1 1 associated with the same file already then it becomes the current output stream Otherwise the file File is opened for output and made the current output stream telling FileName FileName is unified with the name of the current output file if it was opened by te11 1 with the current output stream if it is not user_output otherwise with user told Closes the current output stream and resets it to user_output 7 1 7 An Example Here is an example of a common form of file processing process_file F seeing OldInput see F Open file F repeat read T Read a term process term T Process it T end of file Loop back if not at end of file seen 4 Close the file see O1dInput The above is an example of a repeat loop Nearly all sensible uses of repeat O follow the above pattern Note the use of a cut to terminate the loop 94 SICStus Prolog 7 2 Arithmetic Arithmetic is performed by built in predicates which take as arguments arithmetic expressions and evaluate them An arithmetic expression is a term built from numbers variables and functors that represent arithmetic functions At the time of evaluation each variable in an arithmetic expression must be bound to a non va
497. t will be interpreted as a separate option R abspath Equivalent to the B option except that it builds a saved state for a runtime system instead Under Unix a saved state file can be executed directly by typing file argument This is equivalent to 4 sicstus r file a argument Note Beginning with SICStus version 3 7 saved states do not store the complete path of the binary sp exe Instead they call the start script sicstus which is assumed to be found in the shell s path If there are several versions of SICStus installed it is up to the user to make sure that the correct start script is found Notice that the flags are not available when executing saved states all the command line arguments are treated as Prolog arguments The Development System responds with a message of identification and the prompt as soon as it is ready to accept input thus SICStus 3 7 Mon Mar 2 19 22 44 MET 1998 At this point the top level is expecting input of a directive i e a query or command See Section 1 4 Directives page 12 You cannot type in clauses immediately see Section 1 3 Inserting Clauses Chapter 1 How to Run Prolog 9 page 12 While typing in a directive the prompt on following lines becomes That is the appears only for the first line of the directive and subsequent lines are indented 1 1 1 Finding Libraries at Runtime As of SICStus Prolog 3 7 development system
498. t 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 312 SICStus Prolog 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 31 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 31 4 CHR Debugging page 316 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 S
499. t1 Element Set2 Set2 is like Set1 but with Element removed ord disjoint Set1 Set2 The two ordered sets have no elements in common ord intersect Set1 Set2 The two ordered sets have at least one element in common ord_intersection Set1 5et2 Intersect Intersect is the ordered set representation of the intersection between Set1 and Set2 ord_intersection Set1 Set2 Intersect Diff Intersect is the intersection between Set1 and Set2 and Diff is the difference between Set2 and Set1 ord_intersection Sets Intersection Intersection is the ordered set representation of the intersection of all the sets in Sets Example 208 SICStus Prolog ord intersection 1 2 3 1 2 3 4 3 4 5 I I 3 yes ord member Elt Set is true when Elt is a member of Set ord_seteq Set1 Set2 Is true when the two arguments represent the same set Since they are assumed to be ordered representations they must be identical ord setproduct Set1 Set2 SetProduct Set Product is the Cartesian Product of the two Sets The product is represented as pairs Elem1 Elem2 where Elem1 is an element from Set and Elem2 is an element from Set2 Example ord setproduct 1 2 3 4 5 6 P P 1 4 1 5 1 6 2 4 2 5 2 6 3 4 3 5 3 6 yes ord subset Set1 Set2 Every element of the ordered set Set appears in the ordered set Set2 ord subtract Set1 Set2 Difference Difference contains all
500. tant use for attributed variables is in implementing coroutining facilities as an alternative or complement to the built in coroutining mechanisms In this context it might be useful to be able to interpret some of the attributes of a variable as a goal that is blocked on that variable Certain built in predicates frozen 2 call_residue 2 and the Prolog top level need to access blocked goals and so need a means of getting the goal interpretation of attributed variables by calling Module attribute_goal Var Goal A hook predicate This predicate is called in each module that contains an attribute declaration when an interpretation of the attributes as a goal is needed It should unify Goal with the interpretation or merely fail if no such interpretation is available An important use for attributed variables is to provide an interface to constraint solvers An important function for a constraint solver in the constraint logic programming paradigm is to be able to perform projection of the residual constraints onto the variables that occurred in the top level query A module that contains an attribute declaration has an opportunity to perform such projection of its residual constraints by defining the following predicate Chapter 14 Attributed Variables 195 Module project_attributes QueryVars AttrVars A hook predicate This predicate is called by the Prolog top level and by the built in predicate call_residue 2 in each module that c
501. te values may have to be introduced and the grain size of the constraint solver invocations can be rather small The translation of constraints to library goals has been greatly improved in the current version so these problems have virtually disappeared However for backward compatibility an implementation by compilation to indexicals of the same constraints is also provided An FD predicate may be defined by a single clause Head Constraint where Constraint is an arithmetic constraint or an element 3 or a relation 3 constraint This translation is only available for clauses thus Head cannot be reified In the case of arithmetic constraints the constraint must be over linear terms see Syntax of Indexicals page 301 The memory consumption of the FD predicate will be quadratic in the size of the source code The alternative version of sum 8 in Section 30 10 1 Send More Money page 298 illustrates this technique In the case of element X L Y or relation X L Y the memory consumption of the FD predicate will be linear in the size of the source code The execution time of the initial evaluation of the FD predicate will be linear in the size of the initial domains for X and Y if these domains are infinite no propagation will take place 298 SICStus Prolog 30 10 Example Programs This section contains a few example programs The first two programs are included in a benchmark suite that comes with the distribution The
502. tead 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 C ordering A lt D ordering B C ordering B D ordering C 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 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 Chapter 29 Constraint Logic Programming over Rationals or Reals 261 29 5 2 Turning Answers into Terms In meta programming applications one needs to get a grip on the results computed b
503. teger between X and 0 floor X The value is the float that is the greatest integral value less or equal to X ceiling X The value is the float that is the least integral value greater or equal to X sin X The value is the sine of X cos CX The value is the cosine of X tan X The value is the tangent of X cot X The value is the cotangent of X sinh X The value is the hyperbolic sine of X cosh X The value is the hyperbolic cosine of X tanh X The value is the hyperbolic tangent of X coth X The value is the hyperbolic cotangent of X asin X The value is the arc sine of X acos X The value is the arc cosine of X atan X The value is the arc tangent of X atan2 X Y The value is the four quadrant arc tangent of X and Y acot X The value is the arc cotangent of X acot2 X Y The value is the four quadrant arc cotangent of X and Y asinh X The value is the hyperbolic arc sine of X 96 SICStus Prolog acosh X The value is the hyperbolic arc cosine of X atanh X The value is the hyperbolic arc tangent of X acoth X The value is the hyperbolic arc cotangent of X sqrt X The value is the square root of X log X The value is the natural logarithm of X log Base X The value is the logarithm of X in the base Base exp X The value is the natural exponent of X exp X Y The value is X raised to the power of Y inf The value is infinity as defined in the IEEE standard nan The value is not a number as de
504. tem for the key Key where Ref is its implementation defined identifier The key must be given and only its principal functor is significant Any uninstantiated variables in the Term will be replaced by new private variables along with copies of any subgoals blocked on these variables see Section 2 3 Procedural page 34 recordz Key Term Ref Like recorda 3 except that the new term becomes the last item for the key Key current key KeyName Key Term Key Term is the most general form of the key for a currently recorded term and Key Name is the name of that key This predicate can be used to enumerate in undefined order all keys for currently recorded terms through backtracking 7 11 Blackboard Primitives The predicates described in this section store arbitrary terms in a per module repository known as the blackboard The main purpose of the blackboard is to provide a means for communication between branches executing in parallel but the blackboard works equally well during sequential execution The blackboard implements a mapping from keys to values Keys are restricted to being atoms or integers in the range 33554432 33554431 whereas values are arbitrary terms In contrast to the predicates described in the previous sections a given key can map to at most a single term Each Prolog module maintains its own blackboard so as to avoid name clashes if different modules happen to use the same keys The key arguments
505. tems 8 2 6 Init and Deinit Functions An init function and or a deinit function can be declared by foreign resource 2 If this is the case these functions should have the prototype void FunctionName int when The init function is called by load_foreign_resource 1 after the resource has been loaded and the interfaced predicates have been installed The deinit function is called by unload_foreign_resource 1 before the interfaced predicates have been uninstalled and the resource has been unloaded The init and deinit functions may use the C interface to call Prolog etc Foreign resources are unloaded before saving states and reloaded afterwards or when the saved state is restored see Section 1 10 Saving page 17 Foreign resources are also unloaded when exiting Prolog execution The parameter when reflects the context of the un load_foreign_resource 1 and is set as follows for init functions SP_WHEN_EXPLICIT Explicit call to load_foreign_resource 1 SP_WHEN_RESTORE Resource is reloaded after save or restore For deinit functions SP WHEN EXPLICIT Explicit call to unload foreign resource 1 SP WHEN SAVE Resource is unloaded before save Chapter 8 Mixing C and Prolog 135 SP_WHEN_EXIT Resource is unloaded before exiting Prolog 8 2 7 Creating the Linked Foreign Resource Suppose we have a Prolog source file ex p1 containing foreign f1 pi integer integer foreign f2 p2 integer integer foreig
506. terr pt 3 vel Ruben 92 stream position 2 sse 91 sStream select 3 iii cov ones ee pede VOU 92 SUbLUSE 2s his dere ec Mea tr aes ene eS aerate 203 SuUbStitute 4 icol per V epa 203 Su bB8umes 2 cc hop HH as 205 SUbstimes chk 2 ios iio pr dba UE eda EROS 205 418 SUELA Di arriba 203 Sum Bi a t 276 sSumist 2 1 2 idad 203 SUP a Leroi 250 symmetric closure 2 sss 222 226 syntax error 5 error class sss 103 syntax errors prolog flag 0 107 SIS TOM Dino Gog Tester Pe Cur 217 SISSI Dat akera othr of kara 217 System 2 vh Tunt Bimini bat iude a bond 217 system error 1 error class 103 system type prolog flag 005 107 T CAD e DA A qub DE UA ET 88 tab 2 itane red 88 tan d d unction eel a elise ad ee eee 95 tanh 1 function 0 ccc cece eee 95 taut 2 coire eee Lee ee ee be ee 242 Pelid lete douse tetas ea esis een 361 tcl eval 3 s eyed tienen wis ride ux 361 tcl new 1 a kL oe i ED 361 A O CAFE GER EN CUP E EI einen 93 telling redes 93 term expsn810n 2 arte eher Ia ida T9 term_expansion 4 tine E nnn 79 term hash 2yr eis eee titles pede cpap Redes Bae ols 206 termhash 4 ridad aa 206 term substimer Jn suc ocd resi c3 bres 205 term variables 2 eis sais diga bu debe Shook ee 206 time out 3U 6n ctp ta e RR TU ae Ee 375 tk all events tk do one event 1 option 365 tk destroy window 1 sse 36
507. tes as much as possible of the cut operation saves information in the public search tree on how to later on continue executing the cut operation and then the worker continues with the current work Calls to predicates that produce side effects are required to synchronize i e to proceed only if they are on the leftmost branch of the entire tree If a side effect predicate is reached on a non leftmost branch that branch will have to suspend Suspending and resuming execution branches can be costly as these actions involve copying state The overhead can even outweigh the speedup gained from running in parallel Therefore the use of side effects in parallel computations is discouraged Also see Section 3 5 Programming Considerations page 45 The current work may be endangered i e possibly pruned by some other worker executing cut or raise_exception 1 Such work is called speculative work If there exists untaken work that is less speculative then it might be a good idea to suspend the current work and move to the less speculative one Ali amp Karlsson 92 This functionality called voluntary suspension is implemented in Muse and it improves execution of search for one solution problems dramatically possibly from speed up 1 to nearly linear speed up Unfortunately the moving of workers introduces some overhead typically below 10 percent Therefore it is possible to turn voluntary suspension off for programs searching for all solut
508. th M x list colors display To store the settings of the faces a few lines must be added to emacs For example Customize font lock faces add hook font lock mode hook lambda set face foreground font lock variable name face 00a000 make face bold font lock keyword face set face foreground font lock reference face Blue 26 SICStus Prolog Chapter 2 The Prolog Language 27 2 The Prolog Language This chapter provides a brief introduction to the syntax and semantics of a certain subset of logic definite clauses also known as Horn clauses and indicates how this subset forms the basis of Prolog 2 1 Syntax Terminology and Informal Semantics 2 1 1 Terms The data objects of the language are called terms A term is either a constant a variable or a compound term 2 1 1 1 Integers The constants include integers such as 0 1 999 512 Besides the usual decimal or base 10 notation integers may also be written in any base from 2 to 36 of which base 2 binary 8 octal and 16 hex are probably the most useful Letters A through Z upper or lower case are used for bases greater than 10 E g 15 271111 8 17 all represent the integer fifteen There is also a special notation for character constants E g QA O Nx441 0 N101 are all equivalent to 65 the character code for A 0 followed by any character except backslash is thus read as an integer If 0 is followed by A th
509. the 4th International Conference Volume 1 MIT Press Cambridge MA 1987 Karlsson 92 R Karlsson A High Performance OR parallel Prolog System PhD thesis Depart ment of Telecommunication and Computer Systems The Royal Institute of Technology Stockholm 1992 Kowalski 74 R A Kowalski Logic for Problem Solving DCL Memo 75 Dept of Artificial Intelli gence University of Edinburgh March 1974 Kowalski 79 R A Kowalski Artificial Intelligence Logic for Problem Solving North Holland 1979 Kreuger 91 P Kreuger GCLAII A definitional approach to control In Proceedings of the sec ond Workshop on Extensions of Logic Programming ELP by Eriksson Hallnas and Schroeder Heister eds held at SICS Stockholm Sweden 1991 to be published in Lecture Notes in Artificial Intelligence Springer Verlag Also available as research report SICS R92 09 Lusk et al 90 E Lusk D H D Warren S Haridi et al The Aurora Or Parallel System New Gen eration Computing vol 7 nos 2 3 pp 243 271 1990 McCabe 92 F McCabe Logic and Objects Prentice Hall 1992 O Keefe 90 R A O Keefe The Craft of Prolog MIT Press 1990 Ousterhout 94 John K Ousterhout Tcl and the Tk Toolkit Addison Wesley 1994 Pereira amp Warren 80 F C N Pereira and D H D Warren Definite clause grammars for language analysis a survey of the formalism and a comparison with augmented transition networks in Artificial Inte
510. the file is loaded all predicates in the file go into ModuleName and the predicates of the ExportList are exported When a module declaration is processed all existing predicates in the module are erased before the new ones are loaded A file which contains a module declaration is henceforth called a module file Options is an optional argument and should be a list The only available option is hidden Bool where Bool is false the default or true In the latter case tracing of the predicates of the modules is disabled although spy points can be set and no source information is generated at compile time A module can also be defined dynamically by asserting or loading predicates to it assert m p x creates the module m if it does not already exists and asserts p x to it Chapter 4 The Module System 49 compile m f creates the module m and loads f into m Dynamically created modules have no public predicates 4 4 Importation When a module file is loaded by load_files 1 2 or one of its shorthands see Section 7 1 1 Read In page 73 by default all the public predicates of the module file are imported by the receiving module An explicit list of predicates to import may also be specified Clashes with already existing predicates local or imported from other modules are handled in two different ways If the receiving module is the user module the user is asked for redefinition of the predicate For other r
511. this is done depends on the op erating system and which Java implementation is used but typically there is a environment variable CLASSPATH which contains the path The path can often also be set on the com mandline using an option such as classpath Refer to your Java documentation for more details Before any predicates can be called the SICStus emulator must be initialized This is done by instantiating the SICStus class NOTE This class must only be instantiated once per Java process Multiple SICStus objects are not supported Most methods take a reference to this object as their first argument This is implicit in the rest of this chapter unless otherwise stated The next step is to load the Prolog code This is done by the method load Corresponds to SP 1oadO in the C interface See Section 8 8 2 Loading Prolog Code page 153 Now everything is set up to start making queries In order to make a query the actual query term must be created This is done by creating an object of the SPPredicate class SPPredicate pred new SPPredicate sp connected 4 Chapter 9 Mixing Java and Prolog 175 5 At this point we have created a predicate object for the predicate connected 4 It is now time to create the arguments for the query The arguments are placed in an array which is passed to a suitable method to make the query The arguments consist of objects of the class SPTerm For example if we need two atoms and a var
512. ting Lists onto the current output stream all the clauses in the current interpreted program in the type in module see Section 4 2 Module Spec page 48 Clauses listed onto a file can be consulted back listing Spec Lists all interpreted predicates covered by Spec which has the same for as for spy 1 see Section 6 3 Spy Point page 62 For example listing concatenate 3 reverse m go 2 3 bar _ current atom A tom Atom is an atom known to SICStus Prolog Can be used to enumerate through backtracking all currently known atoms and return each one as Atom current predicate Namoe Head ISO current predicate Namoe Head ISO Name is the name of a user defined or library predicate and Head is the most general goal for that predicate possibly prefixed by a module name This predicate can be used to enumerate all user defined or library predicates through backtracking predicate property Head Property predicate property Head Property Head is the most general goal for an existing predicate possibly prefixed by a module name and Property is a property of that predicate where the possible properties are e one of the atoms built in for built in predicates or compiled or interpreted for user defined predicates or fd constraint for FD predicates see Section 30 9 Defining Primitive Constraints page 290 e theatom dynamic for predicates that have been declared dynamic see Section 5 2 2 Dynam
513. ting with the connecting processes NewClients is the corresponding list of client host addresses see socket _ accept 3 The second form requires one socket not a list for the first argument and returns a stream NewStream if a connection is made current host HostName HostName is unified with the fully qualified name of the machine the process is execut ing on The call will also succeed if HostName is instantiated to the unqualified name of the machine hostname address HostName Host Address hostname address HostName Host Address The Internet host is resolved given either the host name or address HostAddress should be an atom containing the Internet host address in numbers and dots notation The predicate will fail if the host name or address cannot be resolved Chapter 26 Linda Process Communication 231 26 Linda Process Communication Linda is a concept for process communication For an introduction and a deeper description see Carreiro amp Gelernter 89a or Carreiro amp Gelernter 89b respectively One process is running as a server and one or more processes are running as clients The processes are communicating with sockets and supports networks The server is in principle a blackboard on which the clients can write out 1 read rd 1 and remove in 1 data If the data is not present on the blackboard the predicates suspend the process until they are available There are some more predi
514. tion s s 54 nuse flag 2 dtu ER 123 muse lag Fincas os o Quse 123 m se flags 0 2 een et rs 123 muse init lock C function 150 muse lock C function s esses 150 muse max workers C function 150 muse num workers C function 150 mnusecsync 0 oic ies coined bag wien aides ela A eu 123 mnuse trace 125 5x woe on petet ase wen Da ae 124 muse trace Duarte ara 124 muse_un_lock C function 05 150 muse_worker_id C function 150 N name 2 be Ma gach Soe ieee d E Bae Raed Eb eee 111 nan 0 not a number ccc cece eee eee 96 neighbors 3 icee awe death EREA 222 226 neighbours 3 isses 222 226 new array llicucsil ewe aai rajas 189 DOLO Bis usted EU abies bee nhi 202 DON ee Rd E E UR OE HG ada 87 E ipe Eid 87 no doubles 1 0 2i4csaxkabEnUD edihc breit 202 nodebug debugger command sese 67 nodeb g Q va ciii sek eei eere Eres 62 121 noexpand 0 s iiie bb she aA EL EU EIE LEA 266 ofil errors Q e cresc erera cr rer enne 92 DOE O MC M CER 125 ongmembet 2 i 2 08 ds beds 202 n nvar 1 u wwe webs Vete RE EA C RE 110 nospy this debugger command 67 DOSPE sick abies Week iere M oes 63 121 nospyall O eux nien wooed His tanen se 63 121 notify constrained 1 sese 314 notrac 0i 6 ded Oei Mp EUR 62 121 nozip O0 jx Leena RR b Y RE E 62 121
515. to 1 bar a b c 364 SICStus Prolog prolog_event Terme Terms are strings that contain the printed representation of Prolog terms These are stored in a queue and retrieved as Prolog terms by tcl event 3 or tk next event 2 3 An example test event Event tcl new Interp tcl event Interp prolog event dq write zap 42 Event tcl delete Interp The query test event Event will succeed binding Event to the list zap 42 34 3 Tk The following example is a simple Hello world program tk_hello_world tk new Interp tcl eval Interp button b text Hello command destroy _ tcl eval Interp pack b _ tk_main_loop tcl_delete Interp The program brings up a tiny window with a button labeled Hello and is terminated by pressing the button These are the predicates to use Tk from Prolog tk_new Options TclInterpreter Performs basic Tcl and Tk initialization and creates the main window of a Tk appli cation If you don t have a standard Tk installation you can tell Tk where to look for the initialization files by setting the environment variable TK_LIBRARY Options is a list of optional elements according to top_level_events Event handling will be installed in the Prolog top level loop This means that Tk windows and the Prolog prompt can be simultaneously active name ApplicationName Sets the Tk application name The application name will
516. to creep through your program you will see every entry and exit to from every invocation box including compiled code except for code belonging to hidden modules see Section 4 3 Def Modules page 48 You will notice that the debugger stops at all ports However if this is not what you want the following built in predicate gives full control over the ports at which you are prompted 62 SICStus Prolog leash Mode Leashing Mode is set to Mode Leashing Mode determines the ports of invocation boxes 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 can be a subset of the following specified as a list call Prompt on Call exit Prompt on Exit redo Prompt on Redo fail Prompt on Fail exception Prompt on Exception The initial value of Leashing Mode is call exit redo fail exception full leash ing nodebug notrace nozip Switches the debugger off If there are any spy points set then they will be kept but disabled debugging Prints information about the current debugging state This will show 1 Whether undefined predicates are being trapped 2 Whether the debugger is switched on 3 What spy points have been set see below 4 What mode of leashing is in force see below 6 3 Spy points For
517. tput signal is undefined i e the constraint representing the gate is relaxed Assuming that we have found some incorrect output from a circuit we are interesting in finding the faulty gate Two instances of incorrect output are listed in fault_ex 2 fault F1 F2 F3 F4 F5 X Y Cin Sum Cout sat card 0 1 F1 F2 F3 F4 F5 Fi U1 X Cin F2 U2 Y U3 F3 Cout U1 U2 F4 U3 X Cin F5 Sum Y U3 fault_ex 1 Faults fault Faults 1 1 0 1 0 fault_ex 2 Faults fault Faults 1 0 1 0 0 To find the faulty gates we run the query fault_ex I L labeling L I 1 L 0 0 0 1 0 Chapter 28 Boolean Constraint Solver 245 IE L 1 0 0 0 0 I 2 L 0 0 1 0 0 no Thus for input data 1 1 0 gate 4 must be faulty For input data 1 0 1 either gate 1 or gate 3 must be faulty To get a symbolic representation of the outputs interms of the input we run the query fault 0 0 0 0 01 x y cin Sum Cout sat Cout x cin x y y cin sat Sum cin x y which shows that the sum and carry out signals indeed compute the intended functions if no gate is faulty 246 SICStus Prolog Chapter 29 Constraint Logic Programming over Rationals or Reals 247 29 Constraint Logic Programming over Rationals or Reals 29 1 Introduction The clp Q R system described in this document is an instance of the g
518. traints over finite and infinite trees terms You can consult or compile a constraint handler from the CHR library using e g library chr examples gcd compile library chr examples gcd If you want to learn more about the handlers look at their documented source code In addition 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 326 SICStus Prolog 31 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 A 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 A good heuristic is to prefer simplification to simpagation and propagation and to prefer r
519. tring must not be modified Chapter 8 Mixing C and Prolog 139 int SP_get_address SP_term_ref t void pointer Assigns to pointer a C pointer from a Prolog term The term should be an integer which value is constrained according to see Section 8 3 2 Creating Prolog Terms page 137 SP_put_address int SP_get_list_chars SP_term_ref t char s Assigns to s a zero terminated array of characters corresponding to a Prolog list of character codes The array is subject to reuse by other support functions so if the value is going to be used on a more than temporary basis it must be moved elsewhere int SP get list n chars SP term ref t SP term ref tail long n long w char s Copies into s at most n character codes or zeroes from the list t The number of character codes actually written is assigned to w tail is set to the remainder of the list The array s must have room for at least n characters int SP get number chars S P term ref t char s Assigns to s a zero terminated array of characters corresponding to the printed repre sentation of a Prolog number The array is subject to reuse by other support functions so if the value is going to be used on a more than temporary basis it must be moved elsewhere int SP get functor SP term ref t unsigned long name int arity Assigns to name and arity the canonical representation and arity of the principal functor of a Prolog compound term If the value of t is an atom th
520. ts such as failure driven loops Calls of interpreted predicates are synchronized and all interpreted predicates are sequential The debugger also sequentializes the execution All non deterministic built in predicates are sequential However if a parallel predicate is called by ca11 1 its execution is still parallel We have taken pains to preserve the observable sequential semantics during parallel execution This is achieved through synchronizing all built in predicates with side effects As the foreign predicates may involve side effects in principle they should be synchronized too We decided not to synchronize the foreign predicates as this often may not be necessary The user can call the muse_sync 0 built in predicate immediately before the foreign predicate to achieve synchronization see Section 7 16 Muse Pred page 123 46 SICStus Prolog There are application areas where the principle of preserving sequential semantics seriously limits the available parallelism since communication between parallel execution branches becomes virtu ally impossible The principle may even slow down the execution since suspending and resuming execution branches are costly operations One way to overcome these limitations is to use the foreign language interface As an experimental language extension we have furthermore provided a set of primitives which can be used for non synchronized communication These primitives main tain a blackboard i
521. ts for disjunctions all Data is a list of Module InternalName Count This is the finest resolution level counting individual clauses and disjuncts Above PredName is a predicate spec ClauseName is a compound term Pred Name ClauseNumber and InternalName is either ClauseName corresponding to a clause or ClauseName DisjNo Arity AltNo corresponding to a disjunct profile reset Spec Zeroes all counters for predicates covered by Spec which has the same form as for spy 1 see Section 6 3 Spy Point page 62 Chapter 7 Built In Predicates 123 7 16 Muse The following predicates are only defined in the Muse Development System muse_sync A built in predicate that can be used to synchronize for being leftmost in the parallel search tree Its main use is in combination with foreign language interface calls muse_flags This built in predicate lists all current Muse flag settings muse_flag Flag Old muse_flag Flag Old New These examine and or adjust parts of the Muse scheduler state The current value is returned in Old and a new value may be specified in New The state cannot be changed when Muse is executing parallel work It is therefore recommended to perform such changes as the first or best single goal in a top level query If used elsewhere the execution may be aborted if the system cannot perform the change Possible flag values are num_workers Returns in Old the current number of workers
522. ts other information This state is also controlled by the flag unknown see prolog f1ag 3 1 7 Program Execution And Interruption Execution of a program is started by giving the system a directive which contains a call to one of the program s predicates Only when execution of one directive is complete does the system become ready for another di rective However one may interrupt the normal execution of a directive by typing C This C interruption has the effect of suspending the execution and the following message is displayed Prolog interruption h or for help At this point the Development System accepts one letter commands corresponding to certain actions To execute an action simply type the corresponding character lower or upper case followed by RET The available commands in both Development Systems are 16 SICStus Prolog a aborts the current computation c continues the execution e exits from SICStus Prolog closing all files h lists available commands The following commands are also available in the sequential Development System only invokes a recursive top level tN QA o switch on the debugger See Chapter 6 Debug Intro page 59 If the standard input stream is not connected to the terminal e g by redirecting standard input to a file or a pipe the above C interrupt options are not available Instead typing C causes SICStus Prolog to exit and no terminal prompts are printed 1 8 Exiti
523. ture Notes in Computer Science Springer Verlag 1995 Warren 77 D H D Warren Applied Logic Its Use and Implementation as a Programming Tool PhD thesis Edinburgh University 1977 Available as Technical Note 290 SRI Inter national Warren 83 D H D Warren An Abstract Prolog Instruction Set Technical Note 309 SRI Interna tional 1983 Wirth 76 N Wirth Algorithms Data Structures Programs Prentice Hall 1976 Predicate Index Predicate Index UO CUE i dig dete See id putada 36 99 2 bitwise exclusive or uuuus 94 2 boolean eor esse nne 241 B N Disc hagas Gs Hes Reena nha CUM RE REM 277 SS DAA adt 275 EA it coat ste ae oA E c EE ech 277 HES DS ieri bete re Ra arce pde tamen cobre a 275 O ntt ae te tton RT A 275 doo Des do nte ob M nm em a td n e dU re 275 EN I in Coors Ca ea teeta ie Pee ad 276 wc ELE 277 ENS Ses Lise ERI UEM x ead teats vira 277 ENSURE oap e 275 He Dip io e ees bio eie br oa a 275 BES P DIT 277 ES Da EA ACTA NN AAS A idus 275 277 2 boolean add ooocooocooo o 241 2 multiplication 0c eee eee eee 94 9 2 conj nctionzs ze a re RU RR LEY VR ER 99 o 1gmegatlom vcr Mee ers 94 AA a o AAA il miene 94 2 grammar rule 0 0 00004 76 gt 2 3 2 if then else 0 ccc ee eee 99 252 2 if them Lock bes Gee Oe bes RIS 99 ADICON E ec oats att ee t t st a e 74 A a AAA A a nels a ER 94
524. u really want is arithmetic comparison see Section 7 2 Arithmetic page 94 or unification The predicates make reference to a standard total ordering of terms which is as follows e Variables by age oldest first the order is not related to the names of variables e Floats in numeric order e g 1 0 is put before 1 0 e Integers in numeric order e g 1 is put before 1 e Atoms in alphabetical i e character code order e Compound terms ordered first by arity then by the name of the principal functor then by age for mutables and by the arguments in left to right order for other terms Recall that lists are equivalent to compound terms with principal functor 2 For example here is a list of terms in standard order X 1 0 9 1 fie foe X Y foe 0 2 fie 1 1 1 Note the standard order is only well defined for finite acyclic terms There are infinite cyclic terms for which no order relation holds Furthermore blocking goals see Section 2 3 Procedural page 34 on variables or modifying their attributes see Chapter 14 Attributes page 193 does not preserve their order These are the basic predicates for comparison of arbitrary terms Term1 Term2 ISO The terms currently instantiating Term1 and Term2 are literally identical in particu lar variables in equivalent positions in the two terms must be identical For example the query X Y fails answers no because X and Y
525. uate expressions where the structure of the term denoted is not made explicit through the 38 SICStus Prolog use of parentheses The general rule is that it is the operator with the highest precedence that is the principal functor Thus if has a higher precedence than then atb c at b c are equivalent and denote the term a b c Note that the infix form of the term a b c must be written with explicit parentheses i e atb c If there are two operators in the subexpression having the same highest precedence the ambiguity must be resolved from the types of the operators The possible types for an infix operator are xfx xfy yfx Operators of type xfx are not associative it is a requirement that both of the two subexpressions which are the arguments of the operator must be of lower precedence than the operator itself ie their principal functors must be of lower precedence unless the subexpression is explicitly parenthesized which gives it zero precedence Operators of type xfy are right associative only the first left hand subexpression must be of lower precedence the right hand subexpression can be of the same precedence as the main operator Left associative operators type yfx are the other way around A functor named name is declared as an operator of type Type and precedence precedence by the command op precedence type name The argument name can also be a list of names of operators
526. ubexpression of this form not quantified by unionof 3 will cause the evaluation to suspend until the variable is assigned I an integer inf minus infinity sup plus infinity T1 evaluates to S T1 negated T1 T2 evaluates to the sum of S T1 and S T2 T1 T2 evaluates to the difference of S T1 and S T2 T1 T2 evaluates to the product of S T1 and S T2 where S T2 must not be negative T1 T2 evaluates to the quotient of S T1 and S T2 rounded up where S T2 must be positive T1 T2 evaluates to the quotient of S T1 and S T2 rounded down where S T2 must be positive T1 mod T2 evaluates to the modulo of S T1 and S T2 Chapter 30 Constraint Logic Programming over Finite Domains 293 30 9 4 Monotonicity of Indexicals A range R is monotone in S iff the value of R in S is contained in the value of R in S for every extension S of S A range R is anti monotone in S iff the value of R in S is contained in the value of R in S for every extension S of S By abuse of notation we will say that X in R is anti monotone iff R is anti monotone The consistency or entailment of a constraint C expressed as indexicals X in R in a store S is checked by considering the relationship between D X S and S R together with the anti monotonicity of R in S The details are given in Section 30 9 6 Execution of Propagating Indexi cals page 296 and Section 30 9 7 Execution of Checking Indexicals page 296 The solver
527. uca aa 317 CHP MOSPY Lia ot rixa PR rides ite P 320 chrmotrace 0 onn AT 317 chrspy lciiso0ev qal eee el Lee RR 319 chr trace 0 ci ascii ica O at bna 317 CALCULA dar 278 CIrC it 2 25er nro fei ene 278 CLAUSE 24 sot UR debet MIN te hl spare oyna 114 cla se 3 c bende teeth eh ea edad eke adh sea ated 114 Lig Bae ete wets ae 223 A wise i he EIL Du Benois MEN 89 CLOSE CLIGNE O gorra pni ako eae 233 clpfd dispatch global A sess 285 clpfd full answer 0 essen 283 coloring 3 2J 0 552 De errata a Meee he 223 colo ring 3 raare i here beet irae hek 223 command debugger command 05 68 COmpare 3 ce m ee Rex PR CENE PER CERE 98 compile buffer emacs command 20 compile file emacs command 20 compile predicate emacs command 20 compile region emacs command 20 compile i i seat aie a CG Rupe RE 52 74 compiling prolog flag 0008 105 complement 2 Ws eiiim uda pees as 222 conmpoge 32os2o eub iu bv EM PRU 222 compound 1 i vc eene eed La ER CNET mE UTE 110 consistency error 4 error class 103 consult buffer emacs command 20 consult file emacs command 20 consult predicate emacs command 20 consult region emacs command 20 411 CONSUL Dic iii 52 74 context error 3 error class 103 copy term 2 5 b EE
528. uccess SP FAILURE for failure SP ERROR if an error condition occurred In particular uncaught exceptions resulting from calls from C to Prolog raise an error condition In error situations the macro SP errno will return a value describing the error condition int SP errno The function SP error message returns a pointer to the diagnostic message corre sponding to a specified error number char SP error message int errno 8 2 Calling C from Prolog Functions written in the C language may be called from Prolog using an interface in which automatic type conversions between Prolog terms and common C types are declared as Prolog facts Calling without type conversion can also be specified in which case the arguments and values are passed as SP term refs This interface is partly modeled after Quintus Prolog The functions installed using this foreign language interface may invoke Prolog code and use the support functions described in the other sections of this chapter Functions or their equivalent in any other language having C compatible calling conventions may also be interfaced using this interface When referring to C functions in the following we also include such other language functions Note however that a C compiler is needed since a small amount of glue code in C must be generated for interfacing purposes Note also that on some platforms different calling conventions may exist for C functions Check the Release Notes to s
529. uced method ClassName MethodName Flags Used as first argument to foreign 3 when declaring Java methods The first argument is an atom containing the Fully Qualified Classname of the class The second argument is the method name The third argument is a list of flags Possible flags are instance or static indicating whether or not the method is static or non static Non static methods must have an object reference as their first argument This is a reference to the object on which the method will be invoked This term is then used to identify the method in the foreign_resource 2 predicate So to define a foreign resource exporting the non static Java method getFactors in the class PrimeNumber in the package numbers the method 3 term would look like method numbers PrimeNumber getFactors instance The syntax for foreign 3 is the basically the same as for C functions foreign MethodIdentifier java Predicate A hook predicate specifies the Prolog interface to a Java method MethodIdentifier is method 3 term as described above Predicate specifies the name of the Prolog predicate that will be used to call MethodIdentifier Predicate also specifies how the predicate arguments are to be translated into the corresponding Java arguments 9 3 Conversions between Prolog Arguments and Java Types The following table lists the possible values of arguments of the predicate specification to foreign 3 The value declares which
530. uery SP pred ref predicate SP term ref argi The function SP next solution will cause the Prolog engine to find solutions of the open query The SP term refs that you sent with the call to SP open query O will be assigned new values SP next solution will return SP SUCCESS for success SP FAILURE for failure SP ERROR if an error condition occurred int SP next solution SP qid query You can terminate a query in two ways The function SP cut query will only take away the choices created since the corresponding SP open query O The data created in the call are still valid and could be passed to another call The function SP c1ose query will restore the state to what it was before the call to SP open query O If the call created data that you want to keep it must be converted to C data before calling SP c1ose query O Both functions return SP SUCCESS for success and SP ERROR for invalid usage int SP cut query SP qid query int SP close query SP qid query 8 4 3 Calling Prolog Asynchronously A Prolog execution may be interrupted by signals or similar asynchronous events If you wish to call Prolog back from a signal handler you cannot use SP query etc directly The call to Prolog has to be delayed until a time when the Prolog execution can accept an interrupt The function SP event serves this purpose and installs the function func to be called from Prolog when the execution can accept a
531. ulated constraints are unsatisfiable and the current computation branch fails At the end of a successful computation all domains have usually become singletons i e the domain variables have become assigned The domains do not become singletons automatically Usually it takes some amount of search to find an assignment that satisfies all constraints It is the programmer s responsibility to do so If some domain variables are left unassigned in a computation the garbage collector will preserve all constraint data that is attached to them Furthermore the behavior of the predicates assert 1 findall 3 copy_term 2 and friends is undefined on non ground terms containing domain vari ables The heart of the constraint solver is a scheduler for indexicals Van Hentenryck et al 92 and global constraints Both entities act as coroutines performing incremental constraint solving or entailment checking They wake up by changes in the domains of its arguments All constraints provided by this package are implemented as indexicals or global constraints New constraints can be defined by the user Chapter 30 Constraint Logic Programming over Finite Domains 273 Indexicals are reactive functional rules that take part in the solver s basic constraint solving algo rithm whereas each global constraint is associated with its particular constraint solving algorithm The solver maintains two scheduling queues giving priority to the queue of indexicals
532. ules 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 guard_bindings options are still around but there are CHR syntax extensions Section 31 3 3 CHR Syntax page 309 and pragmas Section 31 3 5 CHR Pragmas page 311 offering better grained control 4 The Eclipse library of CHR provided automatic built in labeling through the label with decla ration 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 declaration 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 declar ing Constraint to be passive chr labeling Constraint Id lt gt Guard Constraint chr labeling pragma 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 5 The set of built in predicates for adva
533. umber compound X ISO Checks that X is currently instantiated to a term of arity gt 0 i e a list or a structure callable X Checks that X is currently instantiated to a term valid as a goal i e a compound term or an atom is mutable X Checks that X is currently instantiated to a mutable term see Section 7 8 Modify Term page 113 Chapter 7 Built In Predicates 111 functor Term Name Arity ISO functor Term Name Arity ISO The principal functor of term Term has name Name and arity Arity where Name is either an atom or provided Arity is 0 a number Initially either Term must be instantiated or Name and Arity must be instantiated to respectively either an atom and an integer in 0 255 or an atomic term and 0 In the case where Term is initially uninstantiated the result of the call is to instantiate Term to the most general term having the principal functor indicated arg ArgNo Term Arg ISO Term Term Arg is the argument ArgNo of the compound term Term The arguments are numbered from 1 upwards ArgNo must be instantiated to a positive integer and Term to a compound term List ISO List ISO List is a list whose head is the atom corresponding to the principal functor of Term and whose tail is a list of the arguments of Term e g product 0 n n 1 L L product 0 n n 1 n 1 L p I I n 1 product L L product If Te
534. unconverted Prolog terms in which case the actual arguments received will have the type SP_term_ref Also a C function may return an unconverted Prolog term in which case it must create an SP_term_ref Finally any temporary Prolog terms created by C code must be handled as SP_term_refs SP_term_refs are motivated by the fact that SICStus Prolog s memory manager must have a means of reaching all live Prolog terms for memory management purposes including such terms that are being manipulated by the user s C code Previous releases of SICStus Prolog provided direct access to Prolog terms and the ability to tell the memory manager that a given memory address points to a Prolog term but this approach was too low level and highly error prone The current design is modeled after and largely compatible with Quintus Prolog release 3 SP term refs are created dynamically At any given time an SP_term ref has a value a Prolog term This value can be examined accessed and updated by the support functions described in this section It is important to understand the rules governing the scope of SP term refs in conjunction with calls from Prolog to C and vice versa e When a C function called from Prolog returns all SP_term_refs passed to the function or dynamically created by the function become invalid e When terms are passed to C as a result of calling Prolog those terms and any SP term refs created since the start of the query are only val
535. unction is passed a reference to a character buffer large enough to store an N character string The returned string will be stripped of trailing blanks and converted to a Prolog atom Prolog address C void The C function is passed the address of an uninitialized void The returned value which is constrained according to see Section 8 3 2 Creating Prolog Terms page 137 SP put address will be converted to a Prolog integer Prolog address TypeName 132 SICStus Prolog C TypeName The C function is passed the address of an uninitialized TypeName The returned value which is constrained according to see Section 8 3 2 Creating Prolog Terms page 137 SP_put_address will be converted to a Prolog integer Prolog term C SP term ref The C function is passed a new SP term ref and is expected to set its value to a suitable Prolog term Prolog will try to unify the value with the actual argument Prolog integer C long FO The C function should return a long The value returned will be converted to a Prolog integer Prolog float C double F The C function should return a double The value returned will be converted to a Prolog float Prolog atom C unsigned long F The C function should return an unsigned long The value returned must be the canonical representation of a Prolog atom Prolog chars C char F The C function should return a char The returned string will
536. urce code during a debugging session The inheritance mechanism based on module importation is also described First of all every statically defined object will translate to several Prolog clauses belonging to a unique object module with the same identity as the object identifier Object modules are sig nificantly cheaper to create than ordinary modules as they do not import the built in Prolog predicates The module will contain predicates implementing an object declaration the method code imported methods and parameter transfer predicates These predicates will be described in detail below using the notational convention that variable names in italics are syntactic variables that will be replaced by something else in the translation process 32 9 1 The Inheritance Mechanism The inheritance mechanism is based on the importation mechanism of the Prolog module system When an object is created whether loaded from file or at runtime by new 1 2 the method predicates i e predicates implementing the methods visible in the immediate supers are collected After subtracting from this set the method predicates which are locally defined and those that are specified in the don t inherit list the resulting set is made visible in the module of the inheriting object by means of importation This implies that inherited methods are shared expect dynamic methods Dynamic methods are inherited in a similar way with the big difference that they
537. vari able or compound term whose arguments are distinct variables SomeObject new NewObject Supers NewObject is created with Supers specifying the super objects prototypes Supers is a list containing super specifications A super specification is either an object identifier or a pair Object NotInheritList where NotInheritList specifies methods not to inherit from Object NewObject could be an atom variable or compound term whose arguments are distinct variables The object vehicle is created having the proto object object as super followed by creating moving_van with vehicle as super followed by creating truck object new vehicle vehicle new moving_van moving_van new truck yes truck super X vehicle sub X X moving_van no 32 5 2 Method Additions SomeObject asserta SomeMethod SomeObject assertz SomeMethod SomeObject assert SomeMethod Asserts SomeMethod in SomeObject with normal Prolog semantics Add some facts to vehicle and truck with initial value equal to vehicle assert fuel level vehicle assert oil level vehicle assert location truck assert capacity 1 truck assert total weight yes 340 SICStus Prolog 32 5 3 Parameter Passing to New Objects When new objects are created it is possible to pass parameters The following example shows e How general methods are asserted In the previous examples
538. voke a method that is executed in the context of the message delegation operation object message message Message sending Sends message to object setting Self of the recipient to the recipient i e object If object is omitted the recipient is the object in which the goal textually appears object lt message lt message Message delegation Sends message to object setting Self of the recipient to Self of the sender If object is omitted the recipient is the object in which the goal textually appears Delegation preserves Self The following objects physical_object a and b are written using the default notations for sending and delegation hiding the contextual variable Self physical_object volume 50 amp density 100 amp weight X volume V density D X is V D volume 5 amp density 10 amp Method physical_object lt Method js volume 5 amp density 10 amp Method physical object Method Chapter 32 Prolog Objects 333 Js Notice that the difference between the objects a and b is that a delegates any message except volume _ and density _ to physical object while b sends the message to physical object We may now ask a weight X b weight Y X 50 Y 5000 To get hold of the current contextual object the universal method self S is provided Another way to send a message to Self is to use the constant self So the following two alternative
539. w stricter constraint to the store Eventually the computation reaches a phase when no further refinement of the store can result in a more precise constraint the indexical is entailed by the store and then the agent can cease to exist A necessary condition for the FD predicate to be correctly defined is the following for any store mapping each variable to a singleton domain the execution of the indexicals should succeed without contradiction exactly when the predicate is intended to be true There can be several alternative definitions for the same user constraint with different strengths in propagation For example the definition of plusd below encodes the same X Y T constraint as the plus predicate above but maintaining domain consistency plusd X Y T X in dom T dom Y Y in dom T dom X T in dom X dom Y X in 1 3 Y in 10 20 plusd X Y T X in i 3 Y in 10 20 T in 11 13 21 23 yes This costs more in terms of execution time but gives more precise results For singleton domains plus and plusd behave in the same way In our design general indexicals can only appear in the context of FD predicate definitions The rationale for this restriction is the need for general indexicals to be able to suspend and resume and this ability is only provided by the FD predicate mechanism Chapter 30 Constraint Logic Programming over Finite Domains 295 If the program merely posts a
540. ween X Ys N1 version 1 weak but efficient no threat X Y I X in Y V Y I V 1Y I Y in X M X I V X I version 2 strong but very inefficient version no threat X Y I X in unionof B dom Y N B M B I M B I Y in unionof B dom X B M B I M B I version 3 strong but somewhat inefficient version no threat X Y I X in 4 card Y inf sup V unionof B dom Y B M B I M B I Y in 4 card X inf sup V unionof B dom X B B I B I 300 SICStus Prolog queens 8 L ff L 1 5 8 6 3 7 2 4 30 10 3 Cumulative Scheduling This example is a very small scheduling problem We consider seven tasks where each task has a fixed duration and a fixed amount of used resource TASK DURATION RESOURCE ti 16 2 t2 6 9 t3 13 3 t4 7 7 t5 5 10 t6 18 1 t7 4 11 The goal is to find a schedule that minimizes the completion time for the schedule while not exceeding the capacity 13 of the resource The resource constraint is succinctly captured by a cumulative 4 constraint Branch and bound search is used to find the minimal completion time This example was borrowed from Beldiceanu amp Contejean 94 use_module library clpfd schedule Ss End length Ss 7 Ds 16 6 13 7 5 18 4 Rs 2 9 3 7 10 1 11 domain Ss 1 30 domain End 1 50 after Ss Ds End cumulative Ss Ds Rs 13 labeling
541. where NotInheritList specifies methods not to inherit from Object NewObject could be an atom variable or compound term whose arguments are distinct variables instance Instance Creates a new instance Instance Self will be the class of Instance Instance can be a compound term an atom or a variable In the last case the method generates a unique name for Instance has instance Instance Self has the instance Instance has attribute AttributeSpec Self has the attribute AttributeSpec locally defined or inherited AttributeSpec is on the format Name Arity get Attribute Gets the attribute value s of the attribute specified by the head functor of Attribute The value s are unified with the argument s of Attribute Note this method is inlined when possible Chapter 32 Prolog Objects 343 set Attribute Sets the attribute value s of the attribute specified by the head functor of Attribute The value s are taken from the argument s of Attribute Note this method is inlined when possible assert Fact assert Fact Ref asserta Fact asserta Fact Ref assertz Fact assertz Fact Ref Asserts a new Fact in Self If Self is static the name and arity of Fact must be declared as a dynamic method asserta places Fact before any old facts The other forms place it after any old facts A pointer to the asserted fact is returned in the optional argument Ref and can be used by the Prolog built in predic
542. wo indexicals as shown in the program below This constraint will not fire until one of the queens has been assigned the corresponding indexical does not become monotone until then Hence the constraint is still not as strong as it could be For example if the domain of one queen is 2 3 then it will threaten any queen placed in column 2 or 3 on an adjacent row no matter which of the two open positions is chosen for the first queen Chapter 30 Constraint Logic Programming over Finite Domains 299 The commented out formulation of the constraint captures this reasoning and illustrates the use of the unionof 3 operator This stronger version of the constraint indeed gives less backtracking but is computationally more expensive and does not pay off in terms of execution time except possibly for very large chess boards It is clear that no threat 3 cannot detect any incompatible values for a queen with domain of size greater than three This observation is exploited in the third version of the constraint The first fail principle is appropriate in the enumeration part of this problem use module library clpfd queens N L LabelingType length L N domain L 1 N constrain_all L labeling LabelingType L constrain_all constrain all X Xs constrain_between X Xs 1 constrain all Xs constrain between X _N constrain between X Y Ys N no_threat X Y N Ni is N41 constrain bet
543. would still be a permissible form for not P If these precedence and associativity rules seem rather complex remember that you can always use parentheses when in any doubt Note that the arguments of a compound term written in standard syntax must be expressions of precedence below 1000 Thus it is necessary to parenthesize the expression P Q in assert P QD 40 SICStus Prolog 2 7 Syntax Restrictions Note carefully the following syntax restrictions which serve to remove potential ambiguity associ ated with prefix operators 1 In a term written in standard syntax the principal functor and its following must not be separated by any intervening layout text Thus point X Y Z is invalid syntax 2 Ifthe argument of a prefix operator starts with a this must be separated from the operator by at least one layout char Thus p q r where is the prefix operator is invalid syntax The system would try to interpret it as the structure gt IN m r p 4 That is it would take to be a functor of arity 1 However since the arguments of a functor are required to be expressions of precedence below 1000 this interpretation would fail as soon as the precedence 1100 was encountered In contrast the term p gq r is valid syntax and represents the following structure gt RE o m IN P q 2 8 Comments Comments have no effect on the execution of a prog
544. writes To load the package enter the query use module library sockets socket 4 Domain Socket A socket Socket in the domain Domain is created socket close Socket Socket is closed Sockets used in socket connect 2 should not be closed by socket close 1 as they will be closed when the corresponding stream is closed socket bind Socket AF UNIX 4 Socket Name socket bind Socket AF INET Host Port The socket Socket is bound to the address If Port is uninstantiated the operative system picks a port number to which Port is bound Socket connect Socket AF UNIX SocketName Stream Socket connect Socket AF INET 4 Host Port Stream The socket Socket is connected to the address Stream is a special stream on which items can be both read and written socket_listen Socket Length The socket Socket is defined to have a maximum backlog queue of Length pending connections Socket accept Socket Stream Socket accept Socket Client Stream The first connection to socket Socket is extracted The stream Stream is opened for read and write on this connection For the AF INET domain Client will unified with an atom containing the Internet host address of the connecting entity in numbers and dots notation For other domains Client will not be used 230 SICStus Prolog socket_select TermsSockets NewTermsStreams TimeOut Streams ReadStreams The
545. xplores the first solution to the goal P Note also that the is not read as a disjunction operator in this case instead it is part of the if then else construction The precedence of gt is less than that of see Section 2 6 Operators page 37 so the expression is read as C gt P Q R P gt Q ISO When occurring as a goal this construction is read as equivalent to P gt Q fail 100 SICStus Prolog if P Q R Analogous to if P then Q else R but differs from P gt Q R in that if P Q R explores all solutions to the goal P There is a small time penalty for this if P is known to have only one solution of interest the form P gt Q R should be preferred No cuts are allowed in P otherwise true ISO These always succeed Use of otherwise O is discouraged because it is not as portable as true 0 and because the former may suggest a completely different semantics than the latter false fail ISO These always fail Use of false O is discouraged because it is not as portable as fail 0 and because the latter has a more procedural flavor to it repeat ISO Generates an infinite sequence of backtracking choices In sensible code repeat O is hardly ever used except in repeat loops repeat loop has the structure Head save OldState repeat generate Datum action Datum test Datum I restore OldState The purpose is to repeatedly perform some action on elements which
546. y use module library system Certain predicates described below take names of files or directories as arguments These must be given as atoms and the predicates below will not call absolute file name 2 on them Some predicates are described as invoking the default shell Specifically this means invoking bin sh on UNIX platforms On MSDOS Windows and OS 2 the command interpreter given by the environment variable COMSPEC is invoked datime Datime Datime is a timestamp of the form datime Year Month Day Hour Min Sec con taining the current date and time All fields are integers delete_file FileName 0Options FileName is the name of an existing file or directory Options is a list of options Possible options are directory recursive or ignore If FileName is not a directory it is deleted otherwise if the option directory is specified but not recursive the directory will be deleted if it is empty If recursive is specified and FileName is a directory the directory and all its subdirectories and files will be deleted If the operation fails an exception is raised unless the ignore option is specified delete_file FileName Equivalent to delete_file FileName recursive directory_files Directory FileList FileList is the list of entries files directories etc in Directory make directory DirectoryName Makes a new directory environ Var Value Var is the name of an environment variable a
547. y Prop print Term print Stream Term Hookable portrays or else writes the term Term on the stream Stream or on the current output stream print message Severity Message Hookable portrays or else writes Message of a given Severity on the standard error stream profile data Files Selection Resolution Data Data is the profiling data collected from the instrumented predicates defined in the file s Files with selection and resolution Selection and Resolution respectively not available in Runtime Systems nor in Muse profile reset Files The profiling counters for the instrumented predicates in the file s Files are zeroed not available in Runtime Systems nor in Muse prolog flag FlagName Value Value is the current value of FlagName prolog_flag FlagName OldValue New Value OldValue and New Value are the old and new values of FlagName prolog load context Key Value Value is the value of the compilation loading context variable identified by Key prompt Old New Changes the prompt from Old to New public Specs Not a built in predicate public declaration Summary of Built In Predicates 389 put C put Stream C The next character sent to the stream Stream or to the current output stream is C raise_exception Exception Causes abortion of a part of the execution tree scoped by the closest enclosing on_ exception 3 invocation with its first argument matching Exception
548. y you can restore a saved state with the call SP restore which is the C equivalent of the Prolog predicate restore 1 int SP restore char filename SP load O and SP restore return SP SUCCESS for success or SP ERROR if an error condition occurred Prolog error handling is mostly done by raising and catching exceptions However some faults are of a nature such that when they occur the internal program state may be corrupted and it is not safe to merely raise an exception Memory allocation failures are examples of faults In Runtime Systems the following C macro provides an environment for handling faults int SP on fault Sitmt Message Cleanup which should occur in the scope of a char Message declaration Stmt is run and if a fault occurs Stmt is aborted Message gets assigned a value explaining the fault the Prolog internal 154 SICStus Prolog state is cleaned all queries and SP_term_refs become invalid and Cleanup run If Stmt terminates normally Message is left unchanged For example a fault proof Runtime System could have the structure int main int argc char argv char message SP_initialize argc argv usr local lib sicstus37 bin loop SP on fault main_loop message printf ERROR s n message goto loop exit 0 main_loop Faults that occur outside the scope of SP on fault cause the Runtime System to halt with an error message The following funct
549. y 0 x 0 history tree history_point tree point tree object history_point super point _ history point history point attributes history _ _ history_point display A B _ objects call_super_exp history_point display A B C C history_point print_history A B history_point history_point so_type history_point static history_point move A B C _ objects call super exp history point move A B C E E prolog get module data C history D prolog set module data C history A B D 348 SICStus Prolog history point print history A B _ prolog get module data B history C A format with location history w n C A A history point new A xy D E B _ objects call super exp history point new A xy D E B C C prolog set module data A history D E The directive create object 6 creates the object performs the inheritance by importation and initializes attributes The last argument is a tree representing the ancestor hierarchy during com pilation It is used to check that the load time and compile time environments are consistent 32 9 6 Parameter Transfer As can be seen in the expanded methods above the second additional argument is simply ignored if the object has no parameter In contrast regard the following objects ellipse RX RY Color 4 color Color amp area A A is RX RY 3 14159265 i circl
550. y minimize the number of places where a program has to be changed if the program or its environment is moved to a different location file search path 2 is always called in the user module The predicate exists as a dynamic multifile predicate at startup with a single clause defining an expansion for the library 1 alias file search path library Path library directory Path library directory Directory user library directory Directory A hook predicate This predicate specifies a set of directories to be searched when a file specification of the form library Name is used The predicate exists as a dynamic multifile predicate at startup Directories to be searched may be added by using asserta 1 or assertz 1 see Sec tion 7 9 Modify Prog page 113 assertz user file_search_path home HOME assertz user file_search_path demo home prolog demo assertz user library directory home prolog lib With these declarations the file name demo mydemo would expand to HOME prolog demo mydemo where HOME is interpreted as an environment variable the user s home directory File names of the form library mymodule would be looked up in HOME prolog lib if they cannot be found in the default library directory current input Stream ISO Stream is the current input stream The current input stream is also accessed by the C variable SP curin current output Stream ISO Str
551. y the clp Q R solver You can use the predicates dump 3 and or call_residue 2 for that purpose clp r 2 A B C 10 C D E A lt 10 dump A B C D E a b c d e Constraints Constraints e lt 10 0 a 10 0 c d 2 0 e b c d C 10 0 2 0 A B E 10 0 2 0 A B D A lt 10 0 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 29 5 3 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 elim inated 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 Cclpqr examples eliminat example 2 X0 X1 X2 X3 X4 1 87xX0 452 X1 27 X2 54 X3 56 X4 lt 93 433 X0 10 X1 61 X2 28 X3 29 X4 lt 63
552. y the user In Objects there is an initial prototypical proto object called object from which other objects may be constructed directly or indirectly 328 SICStus Prolog 32 1 Getting Started To load the Prolog Objects library enter the query use_module library objects Prolog Objects defines some new infix and prefix operators and redefines some of the built in ones The following operators become installed op 1200 xfy 1 op 1198 xfx op 1198 fx 1 op 550 xfx lt J op 550 fx lt J 32 2 Declared Objects Declared objects are created when the files defining them are loaded into the system 32 2 1 Object Declaration An object object identifier is declared by writing it in the following form object identifier 1 sentence 1 amp sentence 2 amp sentence n where object identifier is a Prolog term that is either an atom or a compound term of the form functor V1 Vn where V1 Vn are distinct variables The object body consists of a number of sentences possibly none surrounded by braces where each sentence is either a method directive to be executed when the object is created or a method clause A method is a number of method clauses with the same principal functor A method clause has a clausal syntax similar to that of Prolog but instead of usual predicate calls in the body of a clause there are method calls Ordinary Prolog goal
Download Pdf Manuals
Related Search
Related Contents
NV200 MANUAL SET 2U 12bay で 36TB 搭載を実現。 ホットスワップに対応した小型軽量の Notice Kelo-cote Gel la Prononciation et les Mots justes NCC0355 User Manual - 49er Communications Installation Instructions 2014 & Later Harley Programme FOS17 Nikon 26442 Digital Camera User Manual version a versión a version b versión b Copyright © All rights reserved.
Failed to retrieve file