Home

The Wild LIFE Handbook - Dennis J. Darland`s Home Page

image

Contents

1. DEMOS README dictionary lf flowers lf prime 1f Flowers doc display terms lf gauss lf queens lf Gauss doc flo README hamming c schedule lf Schedule doc flo custom lf hamming lf simple 1f SuperLint flo flowerdef lf machine l1f soap lf all demos lf flo gram lf magic lf solve lf boxes lf flo utils lf nl lf xXxxooo lf dictionary c flo xtools lf palette lf KKK Yes A 0 1 E e No gt A system core sh core cannot execute EAE YES A 256 e The function argv returns a list of the command line arguments given as strings Example 8 30 This example illustrates argv wild life apple pie Wild Life Interpreter Version 1 0 Copyright C 1991 93 DEC Paris Research Laboratory No customizing file loaded Research Report Draft March 1994 58 Hassan Ait Kaci et al A argv kkk Yes A udir rmeyer LIFE MODULE wild_life apple pie 8 8 8 Timekeeping The following functions provide an interface to the flow of time e The function cpu time returns the amount of user CPU time in seconds that the Wild LIFE process has used so far The function real time returns the amount of wall clock time in seconds that has elapsed since a particular moment of time in the past The location of this moment of time is fixed for any given Unix system The date of this moment depends on the particular Unix system e The function local time returns a term that represents the loc
2. Research Report Draft March 1994 64 Hassan Ait Kaci et al that thing X Yes Succeeds since int X int that thing X 1 gt X 5 AER NO Subterm int of persistent term oe is persistent and int 5 Example 9 5 This example defines an efficient version of bagof using It is efficient because does incremental copying to the heap That is parts of the term that are already on the heap are not copied non strict local bagof local bagof X G gt M L evalin G Prove G L lt lt evalin X copy_pointer L Record X binding fail Force backtracking oo M copy term L Fa oe Copy persistent term Back onto the stack oe Both bagof and 1ocal bagof execute in linear time 6699 Example 9 6 This example illustrates that on a persistent term the function gt project will nonbacktrackably create a new feature if the required one was not present gt persistent this this q a b c write this q a b c KKK Yes 1 this 2 B KkK Yes B b 2 oe B is bound to a persistent term kc No 1 gt this new B write this new feature is added q a b c new gt Q kc Yes B this q a b c new gt B March 1994 Digital PRL Wild LIFE Handbook 2 k No 1 write this q a b c new gt 9 5 Quoting
3. yy q castor pollux e All these things may be used together p q Y 8 with inv glob castor castor begin pollux 2 end 1s translated into p in castor gt A end in_pollux gt B out castor gt C begin out_pollux gt B q in castor gt C in pollux gt D out castor gt E out pollux gt A r in castor gt E out castor gt D S e Initialization may also be performed at the context level The initialization rule given above should be rewritten An accumulator is initialized if it doesn t appear in the context of the expansion But it is possible to force initialization using init acc_info einstein in_start gt mc2 out_start gt energy pred info t einstein S t with init einstein Is translated into S t in einstein gt mc2 out einstein gt energy You may specify which argument has to be initialized by giving a second argument to init inorout For example this clause S t with init einstein in is translated into Research Report Draft March 1994 120 Hassan Ait Kaci et al S t in einstein gt mc2 out einstein gt This clause S t with init einstein out Is translated into S t in einstein gt out_einstein gt energy If the second argument of init isn t in or out then both are initialized F3 The DCG accumulator
4. Read the variable A a WFGetVar A if a Error checking here for demonstration only fprintf stderr Couldn t read variable A n exit 1 Print the type of A printf The type of A is s n WFType a Get the number of features of A printf A has d features Mn WFFeatureCount a Get the feature equals sum WFGetFeature a equals if sum Error checking here for demonstration only Research Report Draft March 1994 144 Hassan Ait Kaci et al fprintf stderr Couldn t read feature equals Wn exit 1 Get the value of sum value WFGetDouble sum amp 0k if ok Error checking here for demonstration only fprintf stderr sum is not a real number n exit 1 printf sum lg n value Get the first feature You can use NULL in WFGetDouble and WFGetString if you are sure the psi term contains a value of the correct type printf the first feature is s Mn WFGetString WFGetFeature a 1 NULL Get the features as a NULL terminated string array features WFFeatures a if features for i 0 features i 1 printf feature s gt s n features i WFType WFGetFeature a features il free features Recommended else Error checking here for demonstration only fprintf stderr A has no features n exi
5. The Wild LIFE Handbook prepublication edition d ilgji tja l PARIS RESEARCH LABORATORY A ee ee March 1994 Hassan Ait Kaci Bruno Dumant Richard Meyer Andreas Podelski Peter Van Roy The Wild LIFE Handbook prepublication edition Hassan Ait Kaci Bruno Dumant Richard Meyer Andreas Podelski Peter Van Roy March 1994 Digital Equipment Corporation 1994 This work may not be copied or reproduced in whole or in part for any commercial purpose Permission to copy in whole or in part without payment of fee is granted for non profit educational and research purposes provided that all such whole or partial copies include the following a notice that such copying is by permission of the Paris Research Laboratory of Digital Equipment Centre Technique Europe in Rueil Malmaison France an acknowledgement of the authors and individual contributors to the work and all applicable portions of the copyright notice Copying reproducing or republishing for any other purpose shall require a license with payment of fee to the Paris Research Laboratory All rights reserved Abstract This handbook provides a tutorial of the LIFE programming language as well as a complete description of the capabilities of the Wild LIFE 1 0 system Although we have attempted to make the tutorial self contained it is preferable that the reader be familiar with Prolog The tutorial exposes gradually the main components of LIFE in a synthetic approach its o
6. gt A root_sort abc 1 2 3 B root_sort a b c C root_sort 5 67 LEE YES A abc B cons C 5 67 Lists are represented with the sorts cons and nil The lists A B and are parsed identically to cons A B and nil e The function strip X yields a term whose sort is and which has the attributes of X The result has the identically same attributes i e the attributes are not copied This function does not residuate and hence must be used with caution Example 8 13 This example illustrates st rip gt A strip siren noise gt loud sound gt unpleasant db gt 120 KK Yes A db gt 120 noise gt loud sound gt unpleasant Example 8 14 This is an example that shows st rip does not copy the arguments of the stripped term gt Y strip X foo 2 gt bar KK Yes Y 2 gt _A bar X foo 2 gt _A e The function copy pointer X yields a term whose sortis root_sort X and which has the attributes of X The result has the identically same attributes i e the attributes are not copied This function does not residuate and hence must be used with caution e The function copy term X returns a copy of the p term X The copy has no subterms in common with X and has identical structure to X So copy term X f X A f A The copy is not persistent see Section 9 This function does not residuate and hence must be used with caution March 1994 Digital PRL W
7. cellHeight gt 20 se se tConst yLogo y0 charHeightlogo tConst yTitle yLogo 2 cellHeight unit gt 10 Scale X X unit se tConst side scale 50 In this way the values of yLogo yTitle and side are computed at load time and will not have to be recomputed at runtime This technique can of course not be used with dynamic constants but may be really useful if the evaluated constants are used often 15 Compatibility with Prolog It is but a small step for a Prolog programmer to start programming in LIFE If he stays in the Prolog like subset of LIFE then he can start immediately The following is a complete list of the differences that can cause problems porting Prolog programs to LIFE terms have no arity They can have an arbitrary number of arguments and arguments may be added at will at run time Therefore arity can not be used to distinguish predicates In Prolog a functor is a pair F N where F is the functor name and N is the arity In Prolog two functors are unifiable if and only if they have both the same name and the same arity Many Prolog programmers take advantage of this and use the same symbol with different arities to name distinct predicates Clearly this practice is no longer valid in Wild LIFE Indeed two terms with the same principal sort symbol but different numbers of arguments or with different subterm attributes altogether can very well This is
8. medium violet red midnight blue navy blue orange orange red orchid pale green pink plum red salmon sea green sienna sky blue slate blue spring green steel blue light brown thistle turquoise violet violet red wheat white yellow yellow green Research Report Draft March 1994 138 Hassan Ait Kaci et al These are loaded when the X toolkit is loaded and may be used wherever a Color parameter is indicated H 5 The hierarchy of graphical interface objects Here is the object hierarchy of the graphical interface toolkit e Panels panel panel c panel frame menu panel menu panel c menu panel frame slide bar sub panel c slide bar frame v slide bar sub panel c v Slide bar v slide 1 h slide bar sub panel c h slide bar h slide 1 e Buttons push button push c push button text box push button frame on off button on off c on off button led on off button text box on off button frame text field button text field c text field button field text field button frame text field button text box menu button menu button c menu button frame menu button text box menu item item c menu item frame menu item text box
9. 2 AA AB etc A Example 8 19 This example illustrates page width gt page width 60 kkk Yes gt big one abc X def fgh a b c d ijk lmn e f g h i Jj h i 12 23 34 45 a b c d a b 32210000 IXIX KKK Yes gt big A nl write A nl nl pretty write A fail one abc A def fgh a b c d ijk lmn e f g h i j h i 12 23 3 4 45 a b c d cons a b 10000 A A one abc _A def fgh a b c d igk 1mn e f g h 1 3 h 1 12 23 34 45 a b c d cons a b 10000 _A _A KK K No March 1994 Digital PRL Wild LIFE Handbook 51 Example 8 20 This example illustrates print depth print depth 0 Xxx Yes gt X f f f f a kkk Yes MSE uz 1 print depth 1 EXA YES X e fEG 1 print depth 2 kck Yes X 1 print depth 3 kKkK Yes X 1 print depth 4 Yeg X f f f f a Example 8 21 This example illustrates the difference between write and writeq The former prints terms without quotes the latter keeps all single and double quotes gt write f o 0 foo kkk Yes gt writeq f o o EE d o kkk Yes write f o o f 00 KKK Yes gt writeq f o o ue O o kkk Yes Research Report Draft March 1994 52 Hassan Ait Kaci et al Example 8 22 This is an example of a self reproducing query It uses writeg and write to reproduce its input exactly gt cX writeq X write
10. 8 5 1 String calculation The function strlen S string returns the length of S S must be a string So strlen abcdef 6 This function residuates on S i e it waits until S is bound to a specific string The function substr S string P int N int substring or string extraction extracts N characters from string S starting from the character at position P So substr abcdef 2 4 yields bcde It truncates the output if it would go beyond the end of S So substr abcdef 5 4 ed This function residuates on S P and N The function strcon Sl string S2 string string concatenation re turns the string obtained by appending S2 to the end of SI So strcon abc def abcdef This function residuates on S1 and S2 The function str2psi S string M string string to 4 term conversion re turns the term whose name consists of the same sequence of characters as S and which is current to module M see Section 10 page 66 The module name M may be omitted in that case the module in which the call to str2psi textually occurs is taken So str2psi foo foo and str2psi 34 34 The latter is not the integer 34 but a symbol This function residuates on S The function psi2str X v term to string conversion returns the string whose name consists of the same sequence of characters as the root sort of X So psi2str int int This function never residuates Hence it is order dependent and should be used with caution It
11. predicate definition 14 built in function 45 gt built in function 45 gt lt built in function 45 gt built in function 45 lt built in function 45 gt built in function 45 gt lt built in function 46 gt built in function 45 lt built in function 45 A built in function 46 accumulator clause 110 attribute definition 29 Research Report Draft 147 lt built in function 45 built in function 45 disjunction 34 type disjunction 34 see accumulator 117 unification predicate 38 lt built in function 42 gt see accumulator 117 built in function 43 2 built in Prolog 99 built in function 43 built in function 40 lt built in function 47 gt built in function 47 gt built in function 47 built in function 47 lt built in function 47 built in function 47 amp unification function 38 3 built in sort 9 built in predicate 15 34 ib term 7 aliasing 7 arity 97 as array 84 as hash table 11 13 attribute 11 canonical form 49 coreference 7 cycles 12 directed graph 12 feature 7 flexible record 7 label 7 11 matching 21 normal term 62 66 persistent term 61 62 record 7 sharing 12 tag 7 11 unification 12 variable 7 11 March 1994 148 tilde 20 built in sort 9 backquote bui
12. 2 gt 4 pick func fact test Research Report Draft March 1994 26 R F A oo oe oe pick arg A pick func F write Function applied is WR nl fail and let us try it gt test Function 2 gt 4 Function fact appli Function 2 gt 4 Function fact appli Function 2 gt 4 Function fact appli KKK No 6 5 Quote and eval Apply an unknown func Pick an argument Pick a function F to argument A Force backtracking applied to argument 5 ed to argument 5 is 12 applied to argument 3 ed to argument 3 is 6 applied to argument 7 ed to argument 7 is 50 Hassan Ait Kaci et al tion to an unknown argument is 20 0 is 12 is 28 40 Since terms are manipulated as data in Wild LIFE and since functions are evaluated eagerly it is often necessary to prevent such an evaluation to happen This is done quite similarly to Lisp by using a quoting operator It is written as a prefix backquote This distinguishes it from the single quote already used to write symbols that contain non alphanumeric characters A backquoted expression is a term and may be manipulated like any 5 term Example 6 14 This is an example of quoting a functional expression gt X 14 2 Yes X 3 Y 1 2 Yes X 3 Y 1 2 The following built ins are related to quote e The function eval E evaluates the result of
13. O decimal R decimal Y decimal Print the result nd write SEND S E N D nl write MORE t LM O Y R E nl write nl write MONEY M O N E Y nl nl fail decimal gt 0 1 2 3 4 5 6 7 8 9 carry gt 0 1 diff list l diff list H T generate diffs H T diff list T H 9 H 0 generate diffs H generate diffs H A T generate diffs H T A H This program solves the problem very quickly despite the fact that Wild LIFE is only an interpreter It is interesting that this solution is of the same order of efficiency as one based on finite domains import solve File solve lf loaded KK Yes gt solve SEND 9567 MORE 1085 MONEY 10652 KKK No In less than a second on a DECstation 3100 Wild LIFE prints a solution and proves it is unique Just to get an idea of the power of constraints we wrote a program in C which solves the same problem using a generate and test method It has seven nested loops in which the program explicitly tests the difference constraints by marking those digits already used On the same machine its CPU time is 1 0 seconds Notice also that Wild LIFE does no special preprocessing of constraints or static analysis other than sort encoding which isn t used here except for local propagation PThere are presently no finite domains in Wild LIFE as such althoug
14. Wild LIFE Handbook 93 1 Q 3 4 5 6 7 8 9 10 1 Q 3 4 5 6 7 8 9 10 t attr t attr const t attr u t attr u const t u attr t u attr const t attr u v w t attr u v w const t u attrl1 v attr2 w attr3 t u attrl v attr2 w attr3 we const attributes attributes constraint attributes inheritance attributes inheritance constraint same meaning as 3 same meaning as 4 attributes multiple inheritance attributes multiple inheritance constraint attributes multiple inheritance attributes multiple inheritance constraint Table 2 Possible sort declarations Research Report Draft March 1994 94 Hassan Ait Kaci et al leaf tree node tree node left gt tree right gt tree or even the equivalent shorter form leaf tree node left gt tree right gt tree tree Be that as it may we leave it to your taste to choose what fits you best 13 5 Sort encoding Wild LIFE uses a special binary encoding of the declared sorts so that a glb can be quickly and efficiently calculated even if the hierarchy contains a very large number of sort definitions 1 Each declared sort is assigned one bit vector with a value that reflects its place in the hierarchy The value of t
15. X gt f X int gt X write From f X ERE Yes gt p f X p s body is executed f s is not From p MEN YES X Q 1 gt X 1 f s body is now executed From f 1 KKK Yes X 1 Example 6 5 This example illustrates the execution order of functions in interaction with a calling predicate namely unification and with predicates called by such that gt fact2 0 gt 1 gt fact2 N N fact2 N 1 write N Yes gt T fact2 3 T 32 3 k k No 6 3 Matching We describe the problem of matching of two terms as the problem whether the actual ib term the caller matches the formal term the definition This avoids the potential confusion about the direction of matching The actual term matches the formal one if it describes a subset of the set described by the formal 4 term This yields the following conditions for the actual term to match the formal 4 term 1 The root sort of the actual term is a subsort of the root sort of the formal term 2 The 4 terms in the attributes of the formal 4 term are matched by the 1 terms in the corresponding attributes of the actual 4 term which must exist 3 The coreferences the variable aliases of the actual term express at least the coref erences of the formal term The first condition is clear from the sort hierarchy The two root sorts can be equal since a sort is a subsort of itself The second co
16. built in list built in string built in real built in bool built in cons list lt list int real true bool false bool When extending built in sorts it is recommended to respect the following elementary prop erties e int real e glb list real 4 e glb string real e glb list string e glb true false If these properties are not respected then the interpreter may behave in a strange manner it may crash or it may not recognize the built in sorts for what they are 4 1 83 Greatest lower bound glb The gib of two sorts r and s is their largest common subsort Since sorts denote sets the glb corresponds to set intersection There always exists at least one common subsort namely If is the largest common subsort then we say that r and s are incompatible We note that incompatibility is always declared implicitly i e two sorts are incompatible because the user has not declared any common subsort nor is there is a common built in sort except for of course This is in contrast to other hierarchies used for knowledge representation or computational linguistics where the incompatibility has to be declared explicitly The glb of two sorts r and s is not always given by one sort which is declared in the hierarchy Namely if there are several sorts s 5 which are common subsorts of r and s and which are not in a
17. e The function A gt B returns t rue if A is greater than or equal to B in the sort hierarchy e The function A B returns t rue if A is less than B in the sort hierarchy e The function A lt B returns t rue if A is less than or equal to B in the sort hierarchy e The function A B returns t rue if A is equal to B in the sort hierarchy e The function A B returns true if A is comparable to B in the sort hierarchy i e their intersection is non empty e The function A gt B returns t rue if A is not greater than B in the sort hierarchy e The function A gt B returns true if A is not greater than or equal to B in the sort hierarchy e The function A lt B returns t rue if A is not less than B in the sort hierarchy Research Report Draft March 1994 46 Hassan Ait Kaci et al e The function A lt B returns true if A is not less than or equal to B in the sort hierarchy e The function A B returns t rue if A is not equal to B in the sort hierarchy e The function A NV B returns t rue if A is not comparable to B in the sort hierarchy i e their intersection is empty 8 5 Strings A string is a sequence of characters Strings are provided as a separate sort in Wild LIFE Compared to storing character sequences as root sorts of new 1 terms strings use less memory and they are not interned in the symbol table The following built ins are provided to manipulate strings
18. e Type See sort e Undeclared sort An identifier that is an uninterpreted identifier a predicate or a quoted function It is treated as a sort whose only parent is top and whose only child is bottom see also inheritance hierarchy Unification Making two objects equal by restricting the values of each For example the unification of person age gt 25 and woman is woman age gt 25 Unification corresponds to logical equality See Section 4 4 page 12 Uninterpreted identifier An identifier that is not a function predicate or declared sort It is treated as a sort whose only parent is top and whose only child is bottom see also inheritance hierarchy March 1994 Digital PRL Wild LIFE Handbook 105 D Practical information about Wild LIFE 1 0 The system is available by anonymous ftp from gatekeeper dec com After logging in enter the command cd pub plan and then the command bin to enable binary transfer mode Then enter the command get Lifel 0 tar Z to get the system Uncompress and untar this file to obtain the Life1 0 directory See the README file for further instructions The Wild LIFE 1 0 system release contains the following The license agreement The C and LIFE source code of Wild LIFE 1 0 Documentation This includes this handbook a manpage and documentation files for the tools and example programs It also includes a list of known bugs and information about porting Wild LIFE 1 0 to various platforms A set of t
19. gt Color Same as xDrawRectangle but filled with a given color e xFillArc Window X0 Y0 Width Height StartAngle ArcAngle function gt Function color gt Color Same as xDrawArc but filled with a given color e xFillOval Window X0 Y0 Width Height function gt Function color gt Color Same as xDrawOval but filled with a given color e xFillPolygon Window PointsList Function Color Fill a polygon described by a list of points eg 100 100 200 300 300 100 The polygon is closed automatically if the last point of the list does not coincide with the first point March 1994 Digital PRL Wild LIFE Handbook 129 e xLoadFont Display Font FontName string Load the specified font name Valid font names are system dependent They may be found in usr lib X11 fonts The default font name is 9x15 e xDrawString Window X0 Y0 String font gt Font function gt Function color gt Color Draw a string at X0 YO with the specified font on the window The font has to be loaded with xLoadFont This function does not affect the background pixels of the bounding box of the string Note X0 YO is the lower left coordinates of the string The default values and possible values are the same as for xDrawLine e xDrawlImageString Window X0 Y0 String font gt Font function gt Function color gt Color Draw a string at X0 YO with the s
20. methods provided by the routine Encapsulated object oriented process without streams 9 Initialization new counter C counter C 0 Access predicate access X C C X C2 C C2 oe The counter counter inc S V gt counter S V 1 counter set X S V gt counter S X counter see X S V gt counter S V X V counter stoplS V gt true write Counter closed with stop nl counter 1 S V gt counter S V write Message not understood nl counter l V gt true write Counter closed with end of stream This defines a counter process Access to the process is by the variable C The internal state of the process is the value of the counter which is held in V the second argument of counter The use of backtrackable destructive assignment is essential What happens is that counter creates a new object the residuated recursive call through its execution and Research Report Draft March 1994 82 Hassan Ait Kaci et al backtrackable destructive assignment gives this object the same name as the original object which has disappeared This is very close to Actor semantics Here is an example of its use gt new counter C Initialize new counter object KKK Yes C 47 oe 1 access inc C Increment the counter KKK Yes C Q7 2 access inc C Increment the counter KKK Yes C Q7 E
21. x print_codes March 1994 Digital PRL Wild LIFE Handbook 95 e likewise a op where op is a postfix operator is syntactic sugar for op 1 gt a Infix notation is respected by the printer 1f the term has exactly two subterms Otherwise prefix notation is used Prefix notation can always be used even for infix or postfix sort symbols 14 Hints to write more efficient programs 14 1 Garbage collection Garbage collection is expensive The best way to write a program is certainly to avoid using 1t which means that memory should be recovered automatically when possible Using backtracking enables the program to recover memory space without garbage collec tion simply because nearly all the space used between the creation of the choice point and the failure that causes the backtrack is recovered Consider the following example foo 0 foo X X gt 0 foo R X 1 foo R foo R foo R foo N Computes foo 0 4 N times During the query foo 7 Wild LIFE will garbage collect several times before succeeding A way to avoid garbage collection is to force backtracking foo2 0 foo2 X X gt 0 foo2 R X 1 foo2 R foo2 R foo2 R fail succeed Ys The modified predicate 002 7 does not need garbage collection and runs 30 faster This technique may be used if there is no need to keep track of what has been done between the creation of a choice point and the failure Nonbacktrackab
22. 12 10 Method inheritance in the graphical interface toolkit In the graphical interface toolkit supplied with Wild LIFE see appendix H implies is used to perform method inheritance Consider the following sort hierarchy March 1994 Digital PRL Wild LIFE Handbook 87 f lt d f lt e d c e lt c E lt a b a and a predicate p which has one definition per sort p X a pa X pa is a method of sort a p X b pb X pb is a method of sort b Ere p X c pc X pc is a method of sort With implies we can call all methods of p that are supersorts of the argument X This is done by means of the following predicate all_p X p X fail succeed Ys For any X al1_p X will execute all the clauses of p defined for supersorts of X For instance all p X e will execute pa X pc X pe X In the terminology of the graphical interface toolkit imagine now that the sorts are look sorts and p is a drawing routine and you see how looks are inherited In the toolkit the inheritance from boxes looks and constructors i e multiple inheritance is handled using this technique 12 11 Structural constraints and arithmetic constraints Wild LIFE does not do any global constraint solving It does purely local constraint solving In that sense it is more like Prolog than like CLP R Calling a function adds a matching implication constraint and calling a predicate adds a unificat
23. 12 8 Using a 2 term as an array This section presents a Sieve of Eratosthenes program that calculates the sequence of primes up to a given limit It uses a term as an array to store the primality information The features of the term are the integers whose primality are being checked global sieve global limit main write N read_token limit amp int next_prime 2 mils March 1994 Digital PRL Wild LIFE Handbook remove multiples P M cond M limit sieve M multiple of P remove multiples P M P next prime P P lt 1 tg SP imit sieve P SP prime P tg write P remove multiples P 2 P succeed next prime P 1 next pr ime P Here is a sample execution nl nl pretty writeq sieve gt main N 20 2 3 5 f 2 gt 3 gt 4 gt 5 gt 6 gt 7 gt 8 gt 9 gt pp pa pa p ppp P3 9 00 1001 0 NP oO i V AX NES Ii I3 17 19 prime A 2 prime B 3 multiple of A prime C 5 multiple of B prime D 7 m m ltiple of A ltiple of B u Y u multiple of C prime 11 nultiple of B prime 13 n n n p n G ultiple of D multiple of C ultiple of A rime 17 multiple of B prime 19 12 9 Memoization 85 This example shows how asserta ma
24. 65 B is bound to a persistent term oe B no longer exists but the new feature still does Global and persistent variables can be quoted like functions see Section 6 5 page 26 A quoted variable is not dereferenced This allows global and persistent variables to be part of asserted predicates and functions Example 9 7 This example illustrates the use of quoting global variables when asserting a clause global it gt it one two three P p it O q it assert P assert Q KK Yes P p one_two_three Q q it 1 gt No Now it is worth gt p X q Y 2 it xk kx Yes X one_two_three Y 308 SY A listing shows the difference listing p q p one two three q it succeed succeed The same applies for persistent variables Of course for the difference to be obvious their value must be changed and this can only be done with 9 6 Summary of built ins The following built ins are provided for global variables and persistent terms Research Report Draft March 1994 66 Hassan Ait Kaci et al The predicate g1obal A A2 declares Aj A etc as global variables This predicate is non strict i e it does not evaluate its arguments Each argument A is either an uninterpreted identifier or a 4 term of the form V lt E where V is an uninterpreted identifier and E an expression The latter form initializes V with the evaluated r
25. 9 1 Global variables A global variable is a logical variable whose name is visible throughout the program To be precise it is visible from all clauses within its defining module or any module to which it is exported A global variable behaves exactly as if it were an extra parameter passed to all predicates functions and sorts Global variables must be declared Example 9 1 This example illustrates global variables gt global warfare Declare a global variable kKkK Yes gt warfare 34 Unify the variable with 34 Yes 1 write warfare Write the value 34 W Yes 2 write warfare Backtracking undoes the unification e kKkK Yes Global variables are essentially syntactic sugar and a programming convenience They should be used sparsely as program maintainability may suffer otherwise Other than having a larger scope for its name a global variable acts exactly like a local variable March 1994 Digital PRL Wild LIFE Handbook 61 A good example of the use of a global variable possibly combined with backtrackable destructive assignment is to keep track of the reasoning used in some expert system without having to explicitly pass an extra parameter around to all the predicates or functions used 9 2 Persistent terms A persistent term is a 4 term that does not change its value on backtracking It is read only It may not be modified through unification and functions may not residua
26. Section 15 page 97 lists the differences between Prolog and LIFE Research Report Draft March 1994 102 Hassan Ait Kaci et al B Predefined operators This section lists all the predefined operator declarations in Wild LIFE 1 0 As far as possible the declarations have been kept compatible with the ISO Prolog standard which is substantially embodied in most current Edinburgh style Prolog systems Precedence Kind Operators lt lt gt gt S lt lt gt gt lt lt i gt gt gt lt a esie a v ris gt lt HSAN AA mod lt lt gt gt amp backquote March 1994 Digital PRL Wild LIFE Handbook 103 C Glossary Attribute An attribute is a pair consisting of a label or field name or feature and an associated term See Section 4 2 page 11 Bottom The sort that denotes the empty set The occurrence of bottom in a calculation causes an immediate failure and backtracking to the most recent choice point It is written as 1 e Class See declared sort e Constrained sort A declared sort that has a routine attached to it This routine behaves as a daemon or dynamic constraint See Section 7 1 2 page 30 Constraint A constraint is a relation between variables For example A B 4 is a nu meric constraint between A and B and A person age gt B is a structural constraint between A and B The semantics of LIFE can be explained simply in terms of primitive
27. The accumulator preprocessor provides built in definitions that mimic Prolog s DCG trans lation There are a few differences with Prolog DCGs mainly due to the use of 4 terms instead of Herbrand terms The main differences are that the arguments added have features in_dcg and out dcg and that declarations given interactively must be terminated with If expand_load true is called then declarations in a file may be terminated with Example E11 This example shows how to use DCGs in Wild LIFE import accumulators Loading File Tools accumulators lf Loading File Tools std expander lf Loading File Tools acc declarations lf gt a b c gt listing a a in dog gt A out dcg gt _B b in_dcg gt A out dcg gt C c in deg gt C out dog gt B ENE Nes ES 1 Definition The DCG accumulator is predefined as follows acc info dcg Term Xs Ys acc pred gt C Term false Xs Ys The C Terms FoldOk Xs Ys function is used for accumulation Its arguments have the following meaning March 1994 Digital PRL Wild LIFE Handbook 121 e Terms the list representing the non terminals to be recognized e FoldOk a boolean telling whether Terms may be folded into the program or not e Xs the input stream of non terminals e Ys the output stream of non terminals You may replace the C function by your own version set C my C
28. X int foo Y 42 f00 This also residuates kkk Yes X l int foo Y 1 42 f00 esos E 3 X Y This fails KKK No BE 3 X 1 23 This succeeds KkK Yes X 1 23 f00 Y 1 42 f00 6 4 Currying A functional expression is curried if it has one or more missing arguments A function may be curried on any subset of its arguments and the missing arguments may be applied in any order A curried functional expression is itself a function It can be passed around and applied several times March 1994 Digital PRL Wild LIFE Handbook 23 Example 6 7 We define a function f on three arguments which are selected by the labels eggs bacon and toast It returns the list of its three arguments We call it with only two arguments The function f returns a curried form which is bound to A We can apply A any number of times by specifying a third argument which is indexed by the label toast gt f eggs X bacon gt Y toast gt Z gt X Y Z2 gt A f eggs gt a bacon gt b write A f eggs gt a bacon gt b kkk Yes 1 R1 A toast gt c R2 A toast gt d write R1 R2 nl write A a b c a b d f eggs gt a bacon gt b The curried expression A is unchanged Currying is different from residuation A residuated functional expression returns its result which has the value until the function fires The result may be used in further calculations before the function has fi
29. constraints 6 e Declaration See definition e Declared sort A sort that has been defined in a or declaration This declaration corresponds to a class definition in an object oriented language Declared sorts have data and or routines attached to them and they are part of a hierarchy Definition An assertion that is added to the program It is terminated with a period Also known as a declaration Assertions are predicate clauses function rules or sort declarations e Directive A query that occurs in a file e Dynamic routine A routine that may be modified during program execution The use of dynamic routines should be extremely rare In most cases persistent terms should be used instead For more information on persistent terms see Section 9 page 60 For more information on dynamic routines see Section 11 page 71 Feature A feature is the field name of an attribute For example in the term person age gt 25 age is a feature See Section 4 2 page 11 Function A routine that is called by matching and that returns a value Functions do not guess their answer they wait until their arguments are sufficiently instantiated to execute See also matching and Section 6 page 17 e Hierarchy See inheritance hierarchy e Identifier An identifier is any integer or floating point number or character sequence The character sequence must be surrounded by single quotes if it does not start with a lower case letter
30. e item c Features item c action gt Action Action The action associated with the item H 3 4 Sliders A slider is just a moving button It may move either vertically v slider c orhorizontally h slider c inside the box that contains it Features slider c min Min max Max value Value action Action Min Max Value The position of the slider is associated with a real value that is constrained to stay between Min and Max Min and Max must be given by the user Value is a persistent term Action Each time the value of the slider is updated by moving the slider Action is executed March 1994 Digital PRL Wild LIFE Handbook 135 H 4 Looks H 4 1 Look types e text box A text box appears as text text box is of course a subsort of t box Features text box text Text text state gt State text color id gt Tid true text color id gt TTid font id gt Fid offset gt Offset a text box also has the features of t box Text The text appearing in the box Offset Default value is d offset Offset O The text is centered in the box Offset gt 0 The text is flushed left and Offset is the distance between the left border of the box and the beginning of the text Offset lt 0 The text is flushed right and Offset is the distance between the right border of the box and the end of the text State A boolean describing the state of the button State is
31. except if this module is user The predicate import A A2 loads and opens the modules A A etc which are assumed to be in the files of the same name modulo suffix and search path This predicate is non strict i e it does not evaluate its arguments The arguments must be strings For example import works correctly if the file is called tmp fo00 1 and the module is called foo If one of the files or modules does not exist then the remaining files are not loaded an error message is reported and import fails Cyclic loadings are ignored i e a file is only loaded once during the scope of an import even if it occurs in more than one import query This predicate should be used only as a declaration i e in a query and not in a definition The predicate public Ai A2 declares the symbols A A etc as public This predicate is non strict i e it does not evaluate its arguments They may then be accessed by other modules either by a qualified reference as modules symbol or if opened in the other module simply as symbol Typically the public declarations are placed just after the module declaration at the beginning of a module This predicate should be used only as a declaration i e in a query and not in a definition C 9 It is not possible to tamper with another module s private components The call public built_ ins very_private_part from within module user results in an error message
32. prerequisites gt R list lateCalc A R This sort has attached to it the functions earlyCalc and lateCalc to do the calculations Function earlyCalc determines the earliest time that task A can start earlyCalc gt 0 earlyCalc B ListOfActs gt max B earlyStart B duration earlyCalc ListOfActs Function 1ateCalc determines the latest time that A s prerequisites can start and still finish before A starts lateCalc A gt succeed lateCalc A B task ListOfActs gt lateCalc A ListOfActs assign LSB B lateStart min LSB A earlyStart B duration Wait until B is an integer before doing the assignment assign A B int gt succeed A B Taken together the above definitions form a self contained program This program does all the calculation necessary to determine the earliest and latest start time of each task given the dependencies and the durations For example a possible session is import schedule File schedule 1f loaded ER Yes gt Al task duration gt 10 A2 task duration gt 20 A3 task duration gt 30 prerequisites gt A1 A2 RKK Yes Al task duration gt 10 earlyStart gt 0 lateStart gt 10 prerequisites gt A2 task duration gt 20 earlyStart gt 0 lateStart gt 0 prerequisites gt task duration gt 30 earlyStart gt 2
33. type disjunction 34 38 lt 42 43 43 40 lt 47 gt 47 gt 47 47 lt 47 47 amp 38 1 15 34 March 1994 150 backquote 26 abort 56 and 43 apply 88 argv 57 asc 46 assert 74 asserta 74 bagof 36 bestof 36 call_once 35 ceiling 41 children 44 chr 46 clause 75 close 54 cond 34 copy pointer 40 copy term 40 cos 42 cpu time 58 current module 69 delay check 31 display modules 71 display persistent 66 dynamic 74 eval 26 evalin 27 exists file 54 exp 42 expand load 59 fail 34 features 39 floor 41 gc 56 genint 42 get 48 getenv 57 glb 43 global 65 halt 56 has feature 39 implies 38 import 6 70 March 1994 Hassan Ait Kaci et al initrandom 42 1s function 47 is persistent 47 66 is predicate 47 1s_sort 47 least sorts 45 listing 55 load 6 49 load path 49 local time 58 log 42 lub 43 map 24 module 66 60 mresiduate 37 nl 50 non strict 27 nonvar 47 not 43 op 53 open 70 open in 54 open out 54 or 43 page width 50 parents 44 parse 52 persistent 66 pretty write 49 pretty writeq 49 print_codes 94 print_depth 50 private 70 private feature 70 psi2str 46 public 70 put 49 random 42 read 48 read token 48 real time 58 residuate 37 retract 75 root sort 39 Digital PRL Wild LIFE Handbook set in
34. 3 2 1 13 2 Query levels The observant user will notice that the query level shown by the prompt is not always systematically incremented after every query extension In fact the specific rule for increasing the query level is the following if the query extension 1 contains at least one variable or creates a choice point or creates an X window and 2 succeeds then the level is increased Otherwise the level stays the same viz if the query extension fails or contains no variable and succeeds with no choice point Each time interaction goes back to a previous query level the variable bindings corresponding to that level are displayed Example 13 2 This example illustrates the fine points of query level incrementing gt X a Td VES X a The query level is incremented because X appears in the query 1 gt a a Yes X a Despite success the query level is unchanged because no variable appears in the query and no choice point is created 1 a a b b Yes X a Research Report Draft March 1994 90 Hassan Ait Kaci et al The query level is incremented because a choice point was created proving this query extension 2 k Yes X a The level goes back to 1 because the second disjunct b b succeeds without containing a variable nor creating a choice point 1 gt a a b b c c WEE Yes X mg The query level is incremented because a choice point was created proving this query e
35. 8 31 This example illustrates how to use term expansion to provide a simple tracing facility 16A preprocessor that does DCG expansion and much more is included in the system and described in appendix F March 1994 Digital PRL Wild LIFE Handbook 59 expand load true gt term expansion H B H write root sort H nl B gt load tmp x Loading File tmp x lf gt listing third third A B write third ni A 80 0 BIG KkK Yes This will trace the execution of third The file tmp x 1f contains the single clause third L X L _ _ X _ 8 9 1 Defining term expansion clauses The predicate term expansion A B expands the term A into the term or list of terms B The term may be anything at all including a predicate declaration a function declaration or a sort declaration The predicate term expansion is dynamic and may be extended by the programmer Example 8 32 This example shows the initial definition of term expansion Wild Life Interpreter Version 1 0 Copyright C 1991 93 DEC Paris Research Laboratory No customizing file loaded listing term expansion dynamic term expansion o term expansion is a user defined predicate with an empty definition AAA MES 8 9 2 Using term expansion when loading files The predicate expand_load A W modifies the behavior of the load command with respect to term expansio
36. 97 16 Conclusion the experience of Wild LIFE 100 A LIFE versus Prolog 101 B Predefined operators 102 C Glossary 103 D Practical information about Wild LIFE 1 0 105 vii E Manpage F The accumulator preprocessor E1 Accumulators sasea us se ew RUE A E E1 1 Basic examples and syntax lees Fels2 Accumulation 4 oca Yee OPERE RI RUE Book WO FEL3 Otherfeatures s ios a REG 3 Run eph F 2 Operations on accumulators uretra a oe aa E231 Contextof an expansion eee E2 2 Operations ies A xac A E RU ES Th DGG accumulator aco oe qb e DP D etr XAR ORE E341 Definilion rere eR eT ey Een E3 2 DCGsyntax es E3 3 Implementation notes llle F 4 Passed arguments 4 nto ad bec ene de F5 Common problems and debugging F6 Term expansion qa assed aaa G The X interface G 1 Event mask values zs Loo A ss GR ee ee G 2 Primitive control operations llle G 3 Primitive drawing operations llle H The graphical interface toolkit El dhottodietionu 2 a Ada H 2 Boxes and their placement constraints H 2 1 Boxes used as padding len H2 2 Positlonirig 3 a TRES a AA A P23 EISS een a a Sg a a ee ho ee res H24 SiZ soLbOXeS x 2a v RSS d xn RES H2 5 Creating a DOX lt s ts nav den epe EX GT a imos H3 Main COnstructors s uus noe Roe te e ag uat PRSI Panels due ctu SM BORE Dl T GER Gat Oe BUMONS 8 2o IU SL eee eei d t
37. A Might cause a call to the GC n WFGetDouble a NULL Random results might even crash To avoid this problem do not keep values of type PsiTerm in C variables across calls to Wild LIFE The other side of the coin is that thanks to the garbage collector it is not necessary for the C program to worry about freeing memory in LIFE s memory space in fact doing so would corrupt the integrity of the system Currently the only function requiring the C programmer to free memory is WFFeatures which allocates a string array with malloc The array has to be freed with ree The strings within it should be left alone since they are in LIFE s space 1 5 An exhaustive example The following example displays the correct and short cut use of all the current features of the interface Read it carefully as some of these are not documented elsewhere The program generates the following output gt cc g o demo demo c udir rmeyer LIFE MODULE c_life a lm 1X11 gt demo Welcome to Wild LIFE WFInput succeeded and there may be more answers true false failed demo c line 51 C 4 Research Report Draft March 1994 142 Hassan Ait Kaci et al Ss WN E failed demo c line 69 6 7 message three four equals gt 7 The type of A is user message A has 2 features sum 7 the first feature is threetfour feature 1 gt built_in string feature equals built infint Linking X library ok Here
38. At this point you may either make assertions submit queries to be solved or exit by typing the key sequence CTRL D which closes the input stream The query halt can also be used to terminate Wild LIFE Note throughoutthe handbook anything written like this is simulated input or output from the interpreter Upon startup Wild LIFE automatically loads the file wild life This is a convenience to allow you to customize your environment at each session The customization file is first looked for in the current directory and if not found there in your home directory If none is found then Wild LIFE prints the message No customizing file loaded as is done above 3 2 Input syntax Wild LIFE uses essentially the same syntax as ISO Standard Prolog which is very close to the Edinburgh syntax 10 15 19 Unless specifically indicated to be different the same syntactic conventions apply In particular variables are capitalized or start with an underscore whereas everything else is not is the unification predicate defines a clause is the cut predicate etc When we depart from the familiar syntax we will comment on the changes giving our justification for adopting them There are two kinds of user input to Wild LIFE declarations and queries A declaration becomes part of the program and is not executed A query is a question asked of the system The syntactic difference between the two is how they terminate e Declarations are
39. C at the beginning of the current definition Other wise it behaves identically to assert The predicate clause C unifies C with the first rule or clause that is unifiable with it On backtracking unify C with the successive rules or clauses that unify with it C should have root sort or The predicate retract C unifies C with the first rule or clause that is unifiable with it Remove this item from the program database On backtracking unify and remove with the successive rules or clauses that unify with C The predicate set q H E replaces the definition of function H by a function containing the single rule H gt V where V is the result of evaluating the expression E If H is a predicate name or a declared sort then an error message is given 9 setq is obsolete and will not be supported in the compiler Persistent variables provide the same ability in a cleaner fashion and should be used instead see Section 9 page 60 Example programs and programming techniques This section illustrates programming techniques in LIFE through interesting example pro grams For many more examples look at the Examples and Tools directories in the Wild LIFE 1 0 release package 12 1 Generating prime numbers Enumerating all positive integers can be done in an elegant manner by using the definition natural 0 1 natural Defining prime numbers can be done by declaring a sort prime and attaching a prime testing routine to
40. F q in castor gt E in pollux gt F out castor gt G out pollux gt D r in castor gt G out castor gt C S F1 2 Accumulation The principal operation performed by an accumulator is to accumulate The way accumula tion is performed for a given accumulator is specified through acc info declarations These declarations usually contain a predicate or a sequence of predicates used for accumulation that may take three external arguments e the two terms implementing the accumulator In Out e the data to be accumulated X An acc_info declaration contains the name of the accumulator references to these three terms and the accumulation predicate acc_info AccName X In Out acc_pred gt AccPred There are also other optional arguments to acc_info declarations which will be introduced later The syntax for accumulation in a rule is the following X Acc accumulate X in accumulator Acc Example E3 acc info fwd X In Out acc pred gt Out X In pred_info foo fwd foo 4 fwd foo is translated into foo in_fwd gt A out_fwd gt B C 41A foo in fwd gt C out fwd gt B The expression in acc pred just replaces the X Acc goal with the proper arguments instantiated Research Report Draft March 1994 112 Hassan Ait Kaci et al F 1 3 Other features e Initialization An accumulator that has to be ex
41. P will be executed P is executed only once Example 8 7 This example illustrates residuate gt p A write A nl gt residuate A p A AC NES A 1 A B Touch A Write the value of A KKK Yes The predicate residuate is helpful to set breakpoints on variables when debugging i e to perform an action when a variable is touched e The predicate mresiduate L X1 X2 P attaches the predicate P to all the terms in the list L If one of the terms is touched then P is executed P is executed only once even if more than one of the terms is touched Example 8 8 This example illustrates mresiduate gt p A write A nl gt mresiduate A KKK Yes A B Q 1 gt A 2 2 kkk Yes A 2 B 2 gt CR KK No A B 1 gt B 6 6 Research Report Draft ri oe oe oo oo oo B p A p B Touch A All residuations are gone Go back to previous level Residuations reappear Touch B March 1994 38 8 2 Hassan Ait Kaci et al kkk Yes A B 6 All residuations are gone The predicate implies G calls the goal G using matching on the heads of the clauses defining G If the calling argument implies the head of the clause then the match succeeds and the clause body is called Otherwise the match fails and the next clause is called Backtracking to a successful implies call will fal
42. a persistent term Tid The color ID used when State is false The color value is found in main colors see Colors below Default value is d text TTid The color ID used when State is true Default value is d_text Fid The font ID used Default is bold e frame A frame corresponds to the 3D border of a button Features frame frame_state gt State flat gt Flat color_id gt Cid State If State is true the frame is sunken otherwise it is raised State is a persistent term Flat If Flat is true then there is no raised position When State is false the frame appears flat Cid The color ID used The actual color values are found in the persistent variables highlight colors and shade colors Research Report Draft March 1994 136 Hassan Ait Kaci et al e field A field is a colored rectangle Features field field state gt State color id Cid true field color id gt TFid State A boolean describing the state of the button State is a persistent term Cid The color ID used when State is false The color value is found in main_colors see Colors below Default is d_field TFid The color ID used when State is true Defaultis d_selected_field e led An led is just like an LED i e it is a small light that can be on or off Features led led state gt State led on color id gt LedOn led off color id gt LedOff State A boolean describing the state of the led S
43. by load path followed by the Lib Tools and Examples directories 8 7 2 Writing The following built ins are provided for writing to the current stream e The predicate put C int takes the integer ASCII code C of a character and outputs 1t to the current output stream It is a dual to the get predicate e The predicates write A A2 and pretty write Aj A2 print the terms A1 A etc according to the current operator declarations The arguments are printed in lexicographical order of feature names where all integer features are considered to be less than all non integer features The difference between the two predicates is that pretty write will break up and indent a term if the output does not fit on a single line No line feed is issued after either of these two predicates e The predicates writeq A A and pretty writeq A A print the terms A1 Ao etc according to the current operator declarations The 4 terms are printed with all necessary single and double quotes so that the w terms may be read in again with read e The predicate write_canonical X prints its arguments in a canonical form with out operator declarations and adding single and double quotes where necessary so that This makes pretty write run marginally slower and use more memory Research Report Draft March 1994 50 Hassan Ait Kaci et al the arguments may be read in again with read This predicate is useful fo
44. can be made order independent by wrapping it in an other function definition The following definition waits until X lt foo before firing psi2str foo X foo gt psi2str X The function asc S string returns the ASCII code of the first character of the string S An error message is reported if S is not a string This function residuates on S March 1994 Digital PRL Wild LIFE Handbook 47 e The function chr I int returns a string of length one containing the character whose ASCII code is I An error message is reported if I is not an integer This function residuates on I 8 5 2 String comparison The following functions perform string comparisons and return true or false They will residuate if their arguments are not below string in the sort hierarchy The names of all string comparisons start with The names are consistent with the names of the arithmetic comparisons except for string equality and nonequality which use and instead of and 1 e The function A gt B returns t rue if A is greater than B e The function AS gt B returns t rue if A is greater than or equal to B The function AS B returns t rue if A is less than B The function AS lt B returns t rue if A is less than or equal to B The function AS B returns t rue if A is equal to B e The function A B returns t rue if A is not equal to B 8 6 Type checking These boolean functions test whether an identifier i
45. does not currently differentiate between persistent and global variables Example 9 2 This example illustrates persistent variables gt persistent trouble Declare a persistent variable k Yes trouble with harry oe Assign a value to the variable with destructive assignment oe kkk Yes 1 gt write trouble Write the value with_harry kkk Yes 2 write trouble Backtracking has no effect with harry kkk Yes Research Report Draft March 1994 62 Hassan Ait Kaci et al The following commands global tactics gt tactics retreat are not sufficient to make tactics a persistent variable because when backtracking beyond the point where tactics was boundto the persistent term the binding will be lost in particular when returning to the top level command line 9 4 Destructive assignment Wild LIFE provides a clean integration of destructive assignment in a single assignment language The integration is based on two kinds of terms normal and persistent terms The former are backtrackable i e they regain their former values on backtracking The latter are nonbacktrackable i e changes to them are not undone on backtracking Normal and persistent terms may be matched together This results in a flow of information from the persistent to the normal term never in the other direction Any attempt to modify a persistent term except through its destructive assignment ope
46. e back to the answer to goal grandfather A B Observe that in this context variable C no longer exists Let us proceed asking for the father C of B michael 1 father C B d kKkK Yes A john B michael C harry And further whether A john is the father of C harry 2 gt father A C AEDS NES A john B michael C harry To go back to level 2 we type CR KKK No A john B michael C harry Research Report Draft March 1994 6 Hassan Ait Kaci et al We now give up with to go back to top level 2 gt We find incremental querying to be a powerful means of user interaction It is particularly useful for exploring solutions step by step or seeking further information Fine points about incremental querying are given in Section 13 2 3 4 Loading files A program file is a text file composed of definitions and queries A query in a file behaves as a directive does in Prolog Any combination of definitions and queries that are entered by the user may appear in a program file To load a program file simply type the query load filename The filename must be a string i e enclosed in double quotes The suffix 1 is added automatically if necessary If a syntax error occurs in a file being loaded it is reported along with the line number at which it was detected and it causes Wild LIFE to abort further processing and go back to the top le
47. enter and exit single step mode In single step mode an internal goal is printed and then the system waits for user input to continue Pressing CR will execute one internal goal Pressing an integer N followed by CR will execute N internal goals If X is false then single step mode is disabled This is the default If Xis true then single step mode is enabled If X does not exist then single step mode is toggled In single step mode type h to get online help The predicate abort forces an immediate return to the Wild LIFE top level The predicate halt forces an immediate termination of the Wild LIFE process The predicate gc forces an immediate garbage collection No messages are printed unless verbose mode is active March 1994 Digital PRL Wild LIFE Handbook 57 8 8 The Unix system This section summarizes the built ins that allow Wild LIFE to interact with the Unix operating system e The function system S string executes the command S under the shell sh and returns the resulting exit code The function fails with an error message if a shell could not be created or if S is not a string e The function getenv S string returns a string that contains the value of the environment variable S The function fails if and only if the environment variable does not exist The function fails with an error message if S is not a string Example 8 29 This example illustrates system A system ls
48. gives an outline of its contents To aid in understanding Wild LIFE we shall use a special watchful eyes sign 9 9 to highlight specific points where the behavior of Wild LIFE may run counter to conventions or expectations It will act as a conspicuous marking device at the outset of a paragraph to indicate that you should watch out for the observation to follow to avert potential trouble The LIFE compiler will be as compatible as possible with Wild LIFE 1 0 To ensure that your programs will be portable to the compiler they should only make use of built ins documented in this handbook There exist other undocumented built ins We strongly recommend that you do not use undocumented built ins We do not make any guarantees that they will continue to exist in the compiler Life a user manual 20 rather a particular view of object oriented programming dealing essentially with inheritance Research Report Draft March 1994 Hassan Ait Kaci et al Sections 1 3 pages 1 7 Sections 4 7 pages 7 33 The basic properties of the LIFE language and the Wild LIFE system A general introduction to the concepts of LIFE terms the data structure predicates functions and sorts Reference Section 8 page 33 Section 9 page 60 Section 10 page 66 Section 11 page 71 The core set of built in routines The implementation of destructive assignment and the concepts of global variables and persistent terms The module
49. gt listing solvefsolve In module solve solve Amn B 26 A D 10 A EE IED G 10 B Hot 26 oT A ORE J F _K 10 _H list predicate solve Research Report Draft March 1994 108 Hassan Ait Kaci et al diff List LC ES Gray Ay DK _H carry E Garry _B carry _C decimal JF decimal _G decimal _J decimal _D decimal _I decimal _K decimal nl write SEND Ep Ep Gu d nl write MORE v cA D ILE nl write y s nl write MONEY TAS D cy 3E CK nl nl fail kkk Yes halt Exiting Wild Life 1 850s cpu 0 000s gc 0 0 BUGS See the installation s README file for a list of known bugs CURRENT OWNERS rmeyer prl dec com vanroy prl dec com Peter Va AUTHORS OF OBJECT Richard Meyer Peter Van Roy Bruno Dumant Jean Claud Hassan Ait Kaci Herv X Windows AUTHORS OF DOCUMENTATION Hassan Ait Kaci Bruno Dumant Richard Meyer Andreas Podelski Peter Van Roy March 1994 grammar preprocessor Seth Copen Goldstein Richard Meyer n Roy graphical interface toolkit interface Abder Aggoun contributions Digital PRL Wild LIFE Handbook 109 F The accumulator preprocessor The accumulator preprocessor is a powerful tool to simplify the development of large pro grams The preprocessor does a source to source transformation that a
50. in predicate 127 xLoadFont built in predicate 129 xOpenConnection built in predicate 126 xor built in function 43 xPostScriptWindow built in predicate 127 xRefreshWindow built in predicate 127 xRequestNamedColor built in predicate 127 xSetWindowColor built in predicate 127 xSetWindowGeometry built in predicate 127 xShowWindow built in predicate 127 xtools graphical interface toolkit 130 March 1994 The Wild LIFE Handbook prepublication edition Hassan Ait Kaci Bruno Dumant Richard Meyer Andreas Podelski and Peter Van Roy PARIS RESEARCH LABORATORY 85 Avenue Victor Hugo 92563 RUEIL MALMAISON CEDEX FRANCE
51. includes records with other fields as well The term makes no statement regarding the other fields not even whether they exist or not W terms are extensible record descriptions This means that attributes may be added at will at run time even by user input For example a computation may start with the value circle origin gt P and this value can later be refined to circle origin gt P radius gt R An important application of this extensibility is the use of terms as hash tables For ease of use Wild LIFE allows consecutive numeric labels to be implicit For example thing a b c is equivalent to thing 1 gt a 2 gt b 3 gt c The order of attributes is completely irrelevant and so this term can also be written as thing 2 gt Db 3 gt c 1 gt a 4 3 Variables and tags Variables start with underscore or an upper case letter An anonymous variable may be written with a single _ This is in fact equivalent to the top sort Variables can be used to tag a term and then used as explicit handles for referencing the 7 term The syntax used Research Report Draft March 1994 12 Hassan Ait Kaci et al to express the tagging of a 4 term t by a variable X is X t These references may be cyclic i e a variable may occur within a term tagged by it For example X 42 X represents a cyclic list with single element 42 If a variable occurs by itself not tagging a term then it is implicitly consider
52. indexed by labels which are not necessarily consecutive natural numbers There fore arguments are consumed by name and not by position as in the A calculus 3 The usual way of defining currying would be to say f X Y f X Y The definition im posed by labels in Wild LIFE is f Xi Xo f X1 2 gt X2 We get the same result with f Xi X2 f 2 gt X2 X1 Wild LIFE 1 0 cannot parse an expression of the form f X1 2 X It must be written in two parts as F 2 X and F f X1 A curried functional expression F looks like a term and indeed has the same syntax as a w term However it is illegal to unify F with another term It is possible to inspect the arguments of F with the projection or has feature functions More information about the implementation of currying in Wild LIFE may be found in Section 13 1 page 88 Example 6 10 In this example the operator real division is curried and inverted gt A F B F 2 gt A KKK Yes A real B real F 2 gt A 1 gt A 5 KKK Yes A 5 B 25 F 2 gt A Example 6 11 The standard example of a higher order function is the built in function map It is defined as follows map F gt map F HI T 2 F H map F T It takes a function or a variable that will be instantiated to a function e g a curried functional expression and a list and applies the function to every element of the lis
53. is remembered and reused when encountered again An arbitrarily complex proof can be attached to a sort For a given variable the proof will only be executed once when the variable is refined to have that sort or a lower sort The fact that the proof has been executed is immediately available by inspecting the value of the variable s root sort A recursive sort declaration is a declaration that has a compatible sort in a subterm That is a declaration of s1 is recursive if it contains s2 such that glb s1 s2 41 In the current implementation a recursive sort definition such as person spouse gt person will go into an infinite loop because the definition of person is expanded indefinitely To cope with such definitions Wild LIFE uses the declaration del ay_ check A Research Report Draft March 1994 32 Hassan Ait Kaci et al A2 Where Aj A etc are sorts This predicate is non strict i e it does not evaluate its argument delay check delays expanding a term until it has at least one attribute With this declaration the above definition of person is delay check person person spouse gt person This delays the expansion of a term with sort person until that term has at least one attribute The delay check declaration is propagated to all subsorts of person Example 7 5 This is an example of how to use delay_check Given the following declara tions P person best friend gt Q person get along P Q del
54. not a very serious limitation of compatibility as this practice is generally considered a bad one by serious Prolog programmers and Prolog programs can usually be rewritten in a straightforward way to avoid it Research Report Draft March 1994 98 pred A B C pred 1 123 A ESO pred A B C 26 60 94 pred A B C D WARNING pred A B WARNING In Wild LIFE gt pred 1 123 kc Yes pred A eee KK Yes A Gy B gt pred A eee KKK Yes A B 1 pred A eee KKK Yes A Q9 B 1 gt pred eee ES Yes March 1994 predicate predicate 213 2 B C B C D QA C B write A Example 15 1 Consider the following predicate definition pred 4 pred 2 write 1 undefined undefined Hassan Ait Kaci et al unify In fact they may unify even with distinct root sorts as long as these have a non bottom glb and a term may acquire new attributes as a problem is solved i e as more information is learned about the object This is how Prolog and Wild LIFE behave when confronted with the same queries In SICStus Prolog Digital PRL Wild LIFE Handbook 99 e Terms may be cyclic LIFE s terms may be cyclic they are rational trees They are unified correctly matched correctly read correctly written correctly and asserted correctly Terms are read and written as linear text
55. of LIFE Y terms are generalized Prolog terms They are extensible records that are part of a hierarchy They have a root sort which corresponds to the type of the record and attributes fields with values which themselves are 4 terms Fields may be added at will and the record s root sort may be refined at will See Section 4 page 7 Query A question that is asked of the system It ends with a question mark Unless a routine with side effects is called this does not modify the program Residuation What happens with a function call when there is not enough information in the arguments to fire the function nor to fail The function suspends or residuates until there is enough information to decide one way or the other Root sort The principal sort of a wv term For example the root sort of woman age gt 25 is woman It corresponds to the main functor in Prolog e Routine A function or a predicate e Sort An identifier that represents a set of objects A sort corresponds intuitively to a type or class Sorts may be refined for example real may be refined to int See also declared sort undeclared sort and Sections 4 1 page 8 and 7 page 29 Static routine A routine that cannot be modified during program execution Attempting to do so results in an error See Section 11 page 71 e Symbol See identifier e Top The sort that denotes the set of all records It corresponds to an unbound variable in Prolog It is written as
56. or if it contains non alphanumeric characters other than underscore The character sequence may be surrounded by double quotes A quote character inside a quoted sequence is represented by two quotes An identifier is either a declared sort a function a predicate or an uninterpreted identifier The first definition of an uninterpreted identifier as function declared sort or predicate means that identifier will always be in that category Inheritance hierarchy The partially ordered set of all sorts It corresponds to the inheritance hierarchy in an object oriented language It has a top element which represents the set of all possible objects and a bottom element which represents the Research Report Draft March 1994 104 Hassan Ait Kaci et al empty set Label See feature e LIFE Logic Inheritance Functions Equations A programming language that uses 1p terms as its basic data structure and unification and matching as its basic operations Matching Checking whether one object implies the other For example woman age gt 25 implies woman so the match succeeds Matching corresponds to logical implication See Section 6 2 page 19 Predicate A routine that is called by unification and does not return a value Predicates may guess an answer if this answer is incorrect later on control flow will return to the predicate by backtracking and it may produce other answers See Section 5 page 14 W term The basic data structure
57. string wheels int All cars have 4 wheels car wheels gt 4 If the relation car lt vehicle is asserted then any properties attached to car must be compatible with those attached to vehicle 7 1 2 Constrained sorts A sort is given an arbitrary predicate as property with a constrained sort declaration This is written as Head Goal For example X person X age int adds the property X age int to all instances of person This has the same effect as person age gt int A sort attribute declaration is a special case of a constrained sort declaration Both attribute declarations and constrained sort declarations may contain functions The resemblance between a constrained sort definition and the built in function such that is intentional Such that attaches a predicate to a function and a constrained sort definition attaches a predicate to a sort Example 7 3 A rectangle has a length width and area A square is a rectangle with identical length and width rectangle length gt L real width gt W real area gt L W square length gt S width gt S side gt S square lt rectangle Here is an example query gt R rectangle area gt 16 width gt 4 kkk Yes R rectangle area gt 16 length gt 4 width gt 4 1 gt R square kkx Yes R square area gt 16 length gt _A 4 side gt _A width gt A The system makes a distinction between a square and a
58. superfluous The LIFE query A B 4 is more flexible than the Prolog version A is B 4 The LIFE version works with any instantiation pattern of its arguments e Prolog uses t rue 0 and fail 0 to represent success and failure Wild LIFE makes a more consistent choice by using succeed and fail for success and failure and reserving t rue and false for the boolean sorts returned as values of boolean functions e The standard order comparisons 2 2 lt 2 lt 2 gt 2 and gt 2 do not exist These are made obsolete by 1 terms e The univ built in 2 does not exist It is made obsolete by terms e bagof in Wild LIFE does no existential quantification and setof is not imple mented See Section 8 1 page 36 e write 1 and writeq 1 may have any number of arguments in Wild LIFE e Lists are represented with the sort cons instead of the dot functor 2 The dot is a built in function used for field selection For example A oo accesses the field oo of the term A e There is no if then else operator gt 2 Itis replaced by the cond function See Section 8 1 page 34 The symbol gt is used to define function rules Research Report Draft March 1994 100 Hassan Ait Kaci et al e Operator declarations are kept as compatible as possible with the ISO standard for Prolog see appendix B page 102 The following differences exist The operator precedence for gt is 1200 instead of 1050 since it i
59. symbols contain the necessary information to interpret X when it gets bound interpret symbols will residuate until X is no longer E This way if X is instantiated to some symbol foo the first rule will behave exactly like p t 002 A warning is given at expansion time to indicate that variables are expanded using interpret symbols interpret symbols is a non strict predicate Changing the argument names If you want special names to be given to the arguments implementing an accumulator you may specify them in the acc info declaration acc info box in name input out name output With this declaration box will be expanded using input and output instead of in box and out_box March 1994 Digital PRL Wild LIFE Handbook 115 F 2 Operations on accumulators E2 1 Context of an expansion The tools we have described above don t give good answers to some practical questions such as e How can we specify rules like head bodyl in gt In out gt Inter body2 in gt Inter out gt Out The problem here is that the accumulator is not expanded in the head of the clause e How can we link different accumulators together There is no reason why different accumulators always have to be isolated from each other In fact the accumulators expanded in the head of the clause are very important in the expan sion of the clause because only these accumulators are linked the others are just initia
60. system Rule base primitives that have been kept for compatibility with Prolog but whose use is not encouraged Programming techniques Sections 12 14 pages 75 97 Section 15 page 97 Examples and useful information on how to write good programs A full list of the differences between Wild LIFE and Prolog Appendices Appendix A page 101 Appendix B page 102 Appendix C page 103 Appendix D page 105 Appendix E page 106 Appendices F I pages 109 144 A short list of reasons why you should use LIFE instead of Prolog The predefined operators in Wild LIFE A glossary of frequently used terminology Information on what the system release contains how to get it and how to get in touch with other LIFE users The manpage for the system describing the vari ous execution options Documentation of four useful tools the accumu lator preprocessor the X interface the graphical interface toolkit and the C LIFE interface Table 1 Road map of the Wild LIFE handbook March 1994 Digital PRL Wild LIFE Handbook 3 3 Running Wild LIFE 3 1 Getting started To start running the interpreter at the shell level simply invoke the command wild_1i fe The program responds with the following message of identification and the prompt gt when it 1s ready to accept input Wild_Life Interpreter Version 1 0 Copyright C 1991 93 DEC Paris Research Laboratory No customizing file loaded gt
61. terminated by a period e Queries are terminated by a question mark Example 3 1 e Assert that chaplin is funny type funny chaplin then CR e Ask who is funny type funny X followed by CR this will yield the answer X chaplin e Ask for another answer type followed by CR there is no more answer since chaplin is the only funny thing around gt We will use the notation CR to denote a carriage return Research Report Draft March 1994 4 Hassan Ait Kaci et al Spaces tabs and line feeds appearing between tokens are ignored so feel free to indent things as you wish or give input over several lines When you do this the prompt becomes after the first line The system knows when the query or declaration has ended Comments are introduced by and terminate at the end of the line System messages warnings and error messages all start with three stars which make them easy to recognize If the query can be satisfied then Wild LIFE will print the bindings of the query variables followed by the message Yes If the query cannot be satisfied the message No will be printed Example 3 2 Let us assert a few facts defining a paternity relation father john harry kKkK Yes gt father john charles Yes gt father harry michael Yes We assert that X is the grandfather of Y if X is the father of Z and Z is the father of Y gt grandfather X Y fath
62. the cycle fires the function The function result is A true oe kck Yes A true G s a gt t b gt G X G 13 Fine points for would be wizards 13 1 Functional variables and apply When a functional expression F A is evaluated whose function symbol is a variable E it looks as if the expression s root sort is a variable and applied to the arguments In fact this is not what happens in Wild LIFE The syntax F a b c is simply syntactic sugar for apply functor gt F 1 gt a 2 gt b 3 gt c It is converted into this internal form by the parser If the feature functor occurs in F it is ignored The function apply is transparent to the user But you should virtually never need to resort to using it explicitly Only in rare cases is it unavoidable to use it as shown in the following example March 1994 Digital PRL Wild LIFE Handbook 89 Example 13 1 Let us define a function mapkey that is similar to map except that it does not apply the mapped function on its first argument but on a specified position label As Wild LIFE stands now there is no way to do this without explicitly using apply as follows mapkey A E 1 gt mapkey A F H T gt FAH apply functor F mapkey A F T H FAH A We can use this to compute the values of an integer say 10 in cyclic groups Z pZ where the values of p are given in a list gt L mapkey 2 mod 10 1 2 3 4 5 6 7 8 9 Yes L 0 0 1 2 0 4
63. the quoted expression E It does not modify E For example continuing the interaction above March 1994 Digital PRL Wild LIFE Handbook 27 Example 6 15 2 gt Z eval Y e The function evalin E evaluates in place the quoted expression E The quoted expression E is replaced by its result e The predicate non strict P declares that the arguments of P are quoted not evalu ated when the routine is called This predicate should be used only as a declaration i e in a query and not in a definition This predicate is non strict i e it does not evaluate its argument Example 6 16 This is an example of a non strict predicate non strict p gt p X write X gt p 1 2 L4 2 KRR Yes Calling p 1 2 prints the quoted term 1 2 If an argument is shared between a strict and a non strict routine then it is considered non strict That is non strict dominates over strict 6 6 Choosing between matching and unification How does a programmer choose between matching and unification as calling mechanisms Functions are called by matching and predicates are called by unification Matching is one way i e it does not modify its arguments so it can act only as an input passing mechanism Unification is symmetric i e it can act as both an input and an output passing mechanism To modify a function s arguments the built in function E G pronounced E such that G can be used It evaluates and re
64. using the operator to represent sharing and cycles e The interactive user interface is different Additions to the rule base are terminated with and queries are terminated with There is no dummy user file Queries may be extended incrementally See Section 3 2 page 3 for an example e Symbols that represent functions behave differently from Prolog For example A in Prolog will bind A to the atom In Wild LIFE it will create the curried function To use as an uninterpreted symbol in Wild LIFE it must be quoted e g as A with backquote When manipulating arbitrary sequences of characters for example textual output one should use a string instead of a single quoted symbol For example call write to write the character e Strings are represented differently In Prolog a string is a short hand for a list of integer ASCII codes In Wild LIFE a string is sort in its own right All strings are subsorts of the built in sort string This allows a representation for strings in Wild LIFE that uses much less space e Some built ins are different See the chapters on built in predicates and functions for a full list of Wild LIFE s built ins Here is a short list of the important differences ee 0 e functor 3 and arg 3 do not exist The latter is replaced by which is called project For more information see Section 8 2 page 38 e is 2 does not exist because it has become
65. 0 lateStart gt Infinity prerequisites gt A1 A2 A3 This says that task A3 can start the earliest at time 20 Activity A1 has a slack of 10 it can start as early as time O and as late as time 10 without slowing down the project Activity A2 must start at time 0 it cannot start later without slowing down the project Research Report Draft March 1994 78 Hassan Ait Kaci et al The problem may be described mathematically as follows Given n tasks numbered 1 2 A For each task i its duration is denoted d duration its earliest and latest start times are denoted e and earlyStart and lateStart and the set of tasks it depends on is denoted P prerequisites Given are all values of d and P The problem is to calculate the values of e and This reduces to the following set of equations max p ejd dj 1 lt i lt n min ep ej di 1 lt i lt n i li Both the maximum and the minimum operations run over all values of j that satisfy their condition The first equation means that task i cannot start until all the tasks that it depends on have finished The second equation means that task i must end before the earliest start time of all the tasks that depend on it A great advantage of writing the program in LIFE is the order independence The program can be written in a straightforward way by exactly following the equations The given informa tion values of d and P may be given in any o
66. 1 Reading The following built ins are provided for reading from the current stream The predicate get C reads the next character off the current input stream and unifies its ASCII code an unsigned integer with its argument C If that next character is the end of file character CTRL D then get unifies its argument with the symbol end of file Be mindful of the fact that if the argument passed has a sort other than then when the end of file marker is reached the predicate will simply fail as end_of file cannot unify with st ring for instance The predicate read X reads a 4 term off the input stream quotes it and unifies it with its argument X The term being read must be properly terminated The 4 term being read must be consistent with the current set of operator declarations Variable names appearing in the input stream are ignored Example 8 17 This example illustrates read gt read R f X g Y X Typed in by the user kkk Yes R _A g _A The predicate read_token X reads one syntactic token from the input stream quotes it and unifies it with X A token is either a symbol a number a string a variable any non alphanumeric built in or declared operator or delimiters parenthesis bracket brace period etc Variable names appearing in the input stream are ignored Example 8 18 This example illustrates read_token gt read token S foo Typed in by the user KKK Yes S foo 1 r
67. 1 attribute label name space 18 backquote 5 26 backtrackable destructive assignment 62 backtracking 14 34 bagof built in function 36 bagof example program 64 bestof built in function 36 bool built in sort 9 boolean arithmetic 43 boolean function 18 boolean functions 42 42 gt 42 41 7 lt 45 gt gt 45 Digital PRL Wild LIFE Handbook gt lt 45 gt 45 lt 45 gt 45 gt lt 46 A 45 A lt 45 46 lt 45 45 lt 42 43 43 40 lt 47 gt 47 gt 47 47 lt 47 47 and 43 call_once 35 has_feature 39 is_function 47 is persistent 47 66 is_predicate 47 1s_sort 47 nonvar 47 not 43 or 43 var 47 xor 43 bottom sort 9 box see graphical interface toolkit 130 breakpoints 37 built in routines 41 gt function definition 17 lt 42 lt 66 lt lt 41 lt lt 66 Gnheritance declaration 8 gt 42 Research Report Draft 149 gt gt 41 gt 42 VAI 16 41 41 such that 27 35 41 41 conjunction 34 project 38 projection 64 41 A 41 11 41 predicate definition 14 lt 45 gt 45 gt lt 45 gt 45 A 45 gt 45 gt lt 46 A gt 45 A 45 46 attribute definition 29 lt 45 45 disjunction 34
68. 3 access see X C Get the counter s value Yeg C Q07 X 2 This creates a new counter object with initial value 0 which is accessed through C The counter is incremented twice and then its value is accessed 12 6 Classes and instances To teach LIFE to non LIFE users or even non Prolog users it is very important to tie its concepts to concepts that are widely known Two such concepts class and instance which are common in object oriented languages such as C and Smalltalk The declaration and use of sorts can be described precisely in terms of the latter two concepts by the following rules 1 A class corresponds to a sort Classes are declared by sort definitions of which the two basic ones are oe Like a struct this adds fields to a class definition class fieldl valuel field2 value2 o9 o Classl inherits all properties of class2 classi class2 2 Instances are created by mentioning the class name during execution For example executing X int will create an instance of the class int Each mention of int creates a fresh instance Therefore executing X int Y int March 1994 Digital PRL Wild LIFE Handbook 83 creates two different instances of the class int in X and Y We can do gt X int Y int X 56 Y 23 We can refine X to 56 and Y to 23 Obviously this would not be possible if X and Y were the same instance 3 The Wil
69. 3 and NU Prolog s when declarations 14 6 1 Defining functions A function definition consists of one or more function rules These are stored in the assertion base in the same order as they will be tried during execution A function rule is written in the form Head gt Expr where Head is a term whose root sort name f is the name of the function being defined and Expr is a term The rule is read as Head evaluates to Expr Research Report Draft March 1994 18 Hassan Ait Kaci et al Head may not contain any function calls Functions declared sorts and predicates share the same name space That is a given identifier may only be used for one of the three Attribute labels features however have their own independent name space Example 6 1 This example defines the factorial function n n n 1 n 2 1 The result expression of the second rule contains a call to the built in function which is written as an infix operator gt fact 0 gt 1 gt fact N int gt N fact N 1 write fact 5 120 taw Yes Example 6 2 This example defines a function 1ist len L that calculates the length of a list It uses terms to represent the natural numbers 0 for 0 and s T for n 1 if T represents n The call listlen L will residuate if L s value is unknown usually For example the result of 1istlen is the v term s s which represents any n gt 2 This correctly re
70. 4 unique integer generation 42 univ built in Prolog 99 Unix built ins argv 57 getenv 57 system 57 Digital PRL Wild LIFE Handbook upper integer part ceiling 41 var built in function 47 variable 7 11 binding context 4 52 global 60 persistent 61 variable arity routine 56 verbose built in predicate 55 wait declaration MU Prolog 17 96 warning 4 54 watchful eyes 9 9 1 when declaration NU Prolog 17 96 widget see graphical interface toolkit 137 Wild LIFE 1 0 system C interface 140 compatibility with compiler 1 25 71 75 how to get the system 105 undocumented built ins 1 with see accumulator 115 write built in predicate 49 write canonical built in predicate 49 writeq built in predicate 49 X event 126 X interface 126 xCloseConnection built in predicate 126 xco X command 127 xCreateWindow built in predicate 126 xDrawArc built in predicate 128 xDrawImageString built in predicate 129 xDrawLine built in predicate 128 xDrawOval built in predicate 128 xDrawRectangle built in predicate 128 xDrawString built in predicate 129 xFillArc built in predicate 128 xFillOval built in predicate 128 xFillPolygon built in predicate 128 xFillRectangle built in predicate 128 xFreeColor built in predicate 127 xGetEvent built in function 129 xGetWindowGeometry built in predicate 127 Research Report Draft 159 xHideWindow built
71. C is only used during the expansion of your grammar in LIFE clauses so you can and should reset its value to the default after translation with the query reset_C The tokenizer and parser written in LIFE see Tools directory redefine C for their own needs E3 2 DCG syntax The standard DCG syntax is supported by this preprocessor Head Body will expand the DCG accumulator in all predicates of Head and Body even if there is no pred info declaration The other accumulators will be expanded according to the declarations Accumulation in the DCG may be specified either with the above notation X dcg or using the standard list notation of DCGs foo gt 3 bar is translated into foo in dcg gt 3 A out_dcg gt B bar in dcg gt A out_dcg gt B F 3 3 Implementation notes e Folding Terminals The DCG accumulator has been optimized to allow the folding of terminals i e terms to be accumulated in the DCG accumulator A translation of 00 gt bar 1 could be foo in dcg gt A out dcg gt B bar in dcg gt A out dcg gt C C 1 B The last statement may be folded into the bar predicate yielding foo in dcg gt A out dcg gt B bar in dcg gt A out dcg gt 1 B pun Research Report Draft March 1994 122 Hassan Ait Kaci et al This translation is more efficient than the previous one and the meaning of the two clau
72. Constrained sorts can be used to help debugging for example by printing all terms of a given sort each time they have their constraints checked Example 7 6 This example shows how attaching a constraint to int lets one trace all integer calculations A in mite S5 KKK Yes gt A 5 7 5 7 35 KK Yes A 35 1 gt B fact 5 51 4 T 33b o2 a i E Or Ts AS 6 242 120 kkk Yes A 35 B 120 Example 7 7 This example shows how attaching a constraint to cons lets one trace all list calculations gt o Cacons wrrte c l nml kkk Yes A a b c d ToTa av KKK Yes A a b c d 8 Basic built in routines This section summarizes the basic built in functions and predicates of Wild LIFE Research Report Draft March 1994 34 8 1 Hassan Ait Kaci et al Control flow The following built ins provide the ability to modify the execution flow of a program The predicate succeed always succeeds The predicate fail always fails The predicate A B executes predicate A and then predicate B It is a logical conjunc tion The predicate A B creates a choice point and then executes predicate A If on back tracking execution returns to the disjunction then predicate B is executed A B isa logical disjunction The function A B creates a choice point and then returns A as its result If on backtracking execution returns to the disjunction then B is returned as its r
73. E Handbook 69 The following technique gets around the problem Example 10 3 module overload gt public and so forth module charley Also opens syntax and built in private Override syntax locally open overload alias overloadd VV NM 10 4 Summary of built ins e The predicate module M string sets the current module to M The argument M must be a string Typically this predicate is put at the beginning of a file to create a new module Setting the current module to the same module twice or more has no further effect Whenever a file is loaded which switches to a different module the current module reverts to what it used to be once the file is closed This predicate should be used only as a declaration i e in a query and not in a definition e The function current module returns the name of the current module Upon startup the current module is user Example 10 4 X current module kkk Yes X user gt gt module charley XXX Yes charley gt X current_module Xxx Yes X charley charley 1 gt module user kkk Yes X charley There is a good reason for this if the argument were allowed to be any symbol then the symbol is created in the module which was previously current This is undesired behavior Research Report Draft March 1994 70 Hassan Ait Kaci et al The prompt always shows the name of the current module
74. F can be opened for input This is quiet and so can be used for testing the presence of a file The predicate open in F S stream opens the file F for input and selects the stream S as current input The argument S is set to a term whose root sort symbolis st ream containing all information relative to the status of reading from this file This predicate fails with an error message if file F cannot be opened e The predicate open out F S stream opens the file F for output and selects the stream S as current output The argument S is set to a term containing all information relative to the status of writing into this file This predicate fails with an error message if file F cannot be opened e The predicate set input S stream sets the input stream to S The stream S must have been initialized by open in e The predicate set output S stream sets the output stream to S The stream S must have been initialized by open out The predicate close 8 stream closes the stream S which must have been initialized by open in or open out It also flushes the corresponding I O buffer If S was an input stream close S automatically selects stdin as current input stream It behaves analogously for output streams and stdout All streams are closed on normal termination of Wild LIFE March 1994 Digital PRL Wild LIFE Handbook 55 All file handling built ins load import open in open out exists file require a string as filename argu
75. For instance Boxl lr aligned Box2 will force the left side of Box1 to be aligned with the right side of Box2 Boxl cc v aligned Box2 will force the centers of Box1 and Box2 to be vertically v aligned H 2 3 Lists Lists are just syntactic sugar to express the vertical or horizontal alignment of boxes The following list handling primitives are provided vl_list vc list vr list ht list hc list hb_list menu list All these functions are defined as prefix operators Thecallvl list List of Boxes returns the box containing all the boxes of the list such that each of them is 1 above the next one in the list As before 1 stands for left x for right t for top b for bottom and c for center The call menu list List of Boxes first constrains all the boxes of the list to be of the same size then returns vl list List of Boxes Itis very easy to make your own kind of list using the implementation of these as an inspiration March 1994 Digital PRL Wild LIFE Handbook 133 H 2 4 Sizes of boxes A very useful constraint predicate is same size same si List of Boxes will force all the boxes of the list to have the same height and width In the same way same height List of Boxes will force all the boxes of the list to have the same height and same width List of Boxes willforce all the boxes of the list to have the same width Sizes of boxes are computed on the fly
76. Function color gt Color linewidth gt LineWidth Draw the line from X0 YO to X1 Y1 on the window with the given function color and linewidth The default values are Function xCopy Color xBlack and LineWidth xThinLine The possible values of Function are xClear xAnd xAndReverse xCopy xAndInverted xNoop xXor xOr xNor xEquiv xlInvert xOrReverse xCopyInverted xOrInverted xNand xSet e xDrawRectangle Window X0 Y0 Width Height function gt Function color gt Color linewidth gt LineWidth Draw the rectangle starting at upper left corner X0 YO of specified width and height on the window The default values and possible values are the same as for xDrawLine e xDrawArc Window X0 Y0 Width Height StartAngle ArcAngle function gt Function color gt Color linewidth gt LineWidth Draw an arc in the rectangle X0 Y0 Width Height starting at angle StartAngle relative to the 3 o clock position and extent ArcAngle angles given in degrees The default values and possible values are the same as for xbrawLine e xDrawOval Window X0 Y0 Width Height function gt Function color gt Color linewidth gt LineWidth Draw an oval in the rectangle X0 YO Width Height on the window The default values and possible values are the same as for xDrawLine e xFillRectangle Window X0 Y0 Width Height function gt Function color
77. ID 1 inshade colors and highlight colors should be respectively a dark and light version of the same color To load a new color use new color Example H 2 To add to the color table the color with RGB values 180 190 190 type X new color 180 190 190 new color returns the color corresponding to the RGB values Example H 3 To load a new font use new font X new font helvetica bold18 new font returns the font corresponding to the string The string must be one of the names obtained by typing xlsfonts Unix command All widgets objects with their own window in short all subsorts of constructors have a color id feature to set the background color of the window Two font IDs are predefined bold helvetica bold r 14 medium helvetica medium r 14 The following colors are loaded by default aquamarine black blue blue violet brown cadet blue coral cornflower blue cyan dark green dark olive green dark orchid dark slate blue dark slate grey dark turquoise dim grey firebrick forest green gold goldenrod green green yellow grey indian red khaki light blue light grey light steel blue lime green magenta maroon medium aquamarine medium blue medium orchid medium sea green medium slate blue medium spring green medium turquoise
78. RL Research Report 11 Digital Equipment Corporation Paris Research Laboratory Rueil Malmaison France 1991 Hassan Ait Kaci and Andreas Podelski Towards a meaning of LIFE In Jan Maluszy ski and Martin Wirsing editors Proceedings of the 3rd International Symposium on Pro gramming Language Implementation and Logic Programming Passau Germany pages 255 274 Springer Verlag LNCS 528 August 1991 Hassan Ait Kaci and Andreas Podelski Order sorted feature theory unification PRL Research Report 32 Digital Equipment Corporation Paris Research Laboratory Rueil Malmaison France May 1993 William F Clocksin and Christopher S Mellish Programming in Prolog Springer Verlag Berlin Germany 2nd edition 1984 Tim Lindholm and Richard A O Keefe Efficient implementation of a defensible semantics for dynamic Prolog code In Proceedings of the Fourth International Conference on Logic Programming pages 21 39 MIT Press May 1987 Richard Meyer Compiling LIFE Technical Report 8 Digital Equipment Corporation Paris Research Laboratory September 1993 Research Report Draft March 1994 146 Hassan Ait Kaci et al 13 Lee Naish Negation and Control in Prolog Springer Verlag LNCS 238 1986 14 Lee Naish Negation and quantifiers in NU Prolog In Proceedings of the 3rd International Symposium on Logic Programming pages 624 634 Springer Verlag LNCS 225 July 1986 15 Richard O Keefe The Craft of Pr
79. The complete definition is in Tools xtools lf March 1994 Digital PRL Wild LIFE Handbook 139 H 6 Screen objects The screen objects manipulated by the X toolkit are subsorts of looks and or constructors They usually have an additional feature that stipulates how the states of the look and that of the constructor are linked change state Research Report Draft March 1994 140 Hassan Ait Kaci et al The C LIFE interface 1 1 Description This interface provides a simple but powerful means of calling the Wild LIFE interpreter from within C programs Routines are provided to e state facts issue queries recover results extract data from terms manipulate the current query status of Wild LIFE e generate more solutions e reset the system The interface behaves in pretty much the same way as the top level of the Wild LIFE interpreter so being familiar with the interpreter and needless to say the LIFE programming language is necessary This also makes the interface very easy to use No means are provided to build i terms directly other than through successive queries 1 2 A simple example The following is a simple C program that calls Wild LIFE to print Hello World include c_life h main int argc char argv WFInit argc argv WFProve write N Hello World N One can compile it with gt cc o hello hello c c life a lm 1X11 and execute it hello Hello World 1 3 Su
80. The predicate private A A declares the symbols Aj A etc as private That is from now on they are only accessible by qualified reference as modules symbol The private declaration is typically used to implement overloading see Section 10 3 This predicate should be used only as a declaration i e in a query and not in a definition The predicate private_feature Aj A declares the feature names A A etc as private This is important because feature names are public by default This predicate should be used only as a declaration i e in a query and not in a definition The predicate open A A makes all the public symbols from the modules Aj A etc visible from within the current module without having to explicitly qualify them The arguments must strings Example 10 5 This example illustrates opening a module gt open built ins gt write hello hello KK Yes 8This is necessary to prevent the filename symbol from being defined in more than one module March 1994 Digital PRL Wild LIFE Handbook 71 Here the symbol write references built insswrite e The predicate display_modules X toggles or switches the module display mode If X is false then terms are displayed without module names in the same manner as normal terms This is the default If X is true then terms are displayed with their module names The system will then display module xxx instead of xxx This is very u
81. X X writeq X write X X writeq X write X X writeq X write X kc Yes X X writeq X write X Example 8 23 This is a shorter self reproducing query gt X write X put 63 X write X put 63 kk xk Yes X write X put 63 This works because the query is itself a term and hence may be cyclic A question for the reader is an even shorter self reproducing query possible 15 8 7 3 Parsing a string The function parse S string X V returns the term resulting from parsing the string S according to the current operator declarations It sets the flag X to either query declaration or error depending on the status of the parse It sets the flag V set to true if the parsed form contains variables and false otherwise Parse never fails Variable names that appear in S are significant and interpreted in the current context The call parse 1 2 returns the quoted term 1 2 The string S must be properly terminated 669 i e it must end with or Example 8 24 This example illustrates parse gt X 1 Yes X 1 F parse X 3 S G eval F The answer is yes find it March 1994 Digital PRL Wild LIFE Handbook 53 F xX 3 G 4 S declaration X 1 KKK No X 1 1 F parse X 3 S V KKK Yes F X 3 S error V true X 1 The first call to parse correctly returns the term 1 3 In the second call to parse the binding S error is due to the
82. a pure program that terminates the result is always the same A function in a function position is always evaluated unless the function position is non strict in which case the function is returned unchanged A predicate or function can be declared to have non strict arguments through the non strict declaration Research Report Draft March 1994 92 Hassan Ait Kaci et al 13 4 Compact sort definitions A complete facility for sort declarations must allow any combination of e Attaching attributes to a sort This is declared with the operator e Declaring single or multiple inheritance relationships from supersorts This is declared with the operator Multiple inheritance from several supersorts is specified by using more than one declaration or by writing the supersorts as a disjunction e Attaching a constraint to a sort This is declared with the such that operator The above comprise the base primitives that allow all sort declarations possible in Wild LIFE A sort that is declared with one of these primitives is called a declared sort In this section we introduce the built in that often permits declarations with a suggestive relationship to mathematical notation This built in provides no additional expressive power It is pure syntactic sugar Table 2 summarizes all the possible combinations of sort declarations allowed in Wild LIFE Notation t u v w denote sort symbols attr following a sort denotes either a non em
83. acc L listing loop main loop 0 in_myacc gt A out myacc A succeed loop A in_myacc gt B out myacc C D A B loop A 1 in myacc D out myacc C main A B loop A in myacc out_myacc gt B gt main 10 L Yes L 1 2 3 4 5 6 7 8 9 10 The declaration acc_info declares the accumulator myacc The declaration pred_info declares that predicate 100p uses myacc The predicates loop and main are defined using Research Report Draft March 1994 110 Hassan Ait Kaci et al queries with root i e terminated with instead of definitions with root The listing of 1oop and main shows how the accumulator myacc is added Complete explanations of all these items are given below The accumulator preprocessor does a generalization of the DCG Definite Clause Grammar expansion of Prolog Definite Clause Grammars DCGs are the standard example of a preprocessor for a single accumulator which is in this case a difference list This is a standard technique described in Prolog textbooks for example in Sterling and Shapiro s Art of Prolog 19 The Wild LIFE preprocessor replaces Prolog terms by terms The generalized technique called EDCG Extended Definite Clause Grammar was devel oped and implemented for the Aquarius compiler 16 17 It has proven extremely useful in the development of large Prolog programs It has been used by the authors and others to
84. ady been visited The mark is the 4 term Seen which is created locally to term size and hence is guaranteed not to occur in the term being explored After the traversal is finished the algorithm backtracks to unmark all the marked nodes and to recover all memory used during the traversal The result is retained by storing it in an anonymous persistent term with nonbacktrackable destructive assignment The persistent term is created before the choice point so that it is unaffected by the backtracking o Return a list containing the values of all features of X feature values X gt map project 2 gt X features X Sum all the elements in a list Research Report Draft March 1994 84 Hassan Ait Kaci et al sum V Vs gt V sum Vs sum gt 0 term size X gt N V Q oo reate an anonymous persistent erm for the result V term explore X Seen Calculate the size fail Remove effects of calculation C t oe oo i N copy_term V s oe Copy the result back to a normal logical term oe term explore X Seen gt V X Seen V 0 oo Skip already counted nodes FV feature values X Get the features of X X Seen Mark X as having been counted V 1 sum map term explore 2 gt Seen FV ys oe Here is a sample execution gt A term size p a b c d KK No gt A term_size B a b B Yes A 4 B a b B
85. ained because the variable L3 is used as a place holder for the result Here is an example execution showing that append1 and append2 behave the same if their arguments are instantiated gt A append1 1 2 3 4 KkK Yes A 1 2 3 4 B 14 24 34 append2 1 2 3 4 B 4 In the following example execution of append1 the arguments are not instantiated at the call gt A appendl B C k Yes A B C Q 1 B 1 2 A NES A A 1 B 2 C B _A _B The call residuates which is marked by the tilde until B is sufficiently instantiated In the following example execution of append2 the arguments are not instantiated at the call gt append2 B C A KKK Yes A cogi Buy we Ae gt 7 ACE YES A _A C BE A Cos ub March 1994 Digital PRL Wild LIFE Handbook 29 EF Yes A _A _BIC B A B C In contrast to appendl1 append2 attempts to guess the right solution It returns longer and longer possible solutions on backtracking 7 Constrained sorts In Section 4 1 1 page 8 we saw how to define a simple sort hierarchy In practice LIFE has more to offer itis possible to attach properties attributes or arbitrary constraints to sorts These properties are verified during execution and are inherited by subsorts Example 7 1 This example ensures that all terms with sort person have an age field whose value is an intege
86. al time For ex ample the goal write local time will write time day gt 14 hour gt 18 minute gt 9 month gt 10 second gt 35 weekday gt 3 year gt 1992 if the date is Wednesday Oct 14 1992 6 09 35 pm The month field ranges from 0 to 11 where 0 represents January The day field gives the day of the month and ranges from 1 to 31 The weekday field ranges from 0 to 6 with O representing Sunday The hour field ranges from 0 to 23 24 hour clock where 0 represents midnight The minute and second fields range from 0 to 59 This function is based on the underlying Unix date and time library 8 9 Loading files with term expansion The standard way in Wild LIFE to run a preprocessor on program rules is to define the preprocessor as a predicate Program rules are written as queries to the preprocessor For example a DCG Definite Clause Grammar expander could be written by defining a predicate named gt declaring it as an operator and then writing clauses as calls to gt namely as queries Head gt Body Because it is awkward to treat program rules as queries in this way Wild LIFE provides a term expansion facility It generalizes the similarly named facility of Prolog Term expansion is useful to expand terms into facts without having to write these terms as queries and without having to define their main functor as a predicate or a function Term expansion is done only when loading files Example
87. ally modified by the window manager e sub panel c A simple sub window that deals with refresh events It is used by slide bars Research Report Draft March 1994 134 Hassan Ait Kaci et al H 3 2 Buttons The following button types are provided listed with the relevant features push c action gt Action on off c on gt On action gt Action text field c action gt Action menu button c menu gt Menu Action Buttons of sort on off c push c text field c have a feature action that describes the action activated by the button The default action is succeed If the button is an on off c ora push c the action is activated each time the mouse is pressed and released inside the button If the button is a text ield c the action is activated each time the return key is pressed and the button active On Buttons of type on_off_c have a boolean feature on that describes their state On is a persistent term Menu A menu button has a feature menu that must contain a term of sort menu panel c To distinguish between the mouse buttons a persistent variable button pressed is modified each time a mouse button is pressed Its value is 1 for the first button 2 for the second button etc H 3 3 Menus e menu panel c Amenu panel c is essentially a panel c with a different kind of window A menu panel is always positioned under its associated menu button In fact a menu panel may contain any object exactly like a panel
88. amming with accumulators 114 method inheritance example program 86 methods 81 module built in predicate 66 69 modules standard built ins 67 syntax 67 user 67 x 67 mouse event 129 mresiduate built in predicate 37 MU Prolog language 17 multiple inheritance 8 92 130 Research Report Draft 155 example program 87 multiplication 41 name space 18 60 66 narrowing 19 natural logarithm 42 navigating the sort hierarchy 43 negation as failure 16 nil built in sort 9 nl built in predicate 50 non interned symbol 9 46 non strict built in routines backquote 26 bagof 36 bestof 36 delay check 31 dynamic 74 global 65 import 70 listing 55 load 49 non strict 27 op 53 persistent 66 public 70 static 74 non strict built in predicate 27 nonbacktrackable destructive assignment 62 nonvar built in function 47 normal term 62 66 not built in function 43 NU Prolog language 17 object orientation 76 object oriented 29 81 103 op built in predicate 53 open built in predicate 70 open in built in predicate 54 open out built in predicate 54 operator declaration 53 predefined 102 or built in function 43 order of execution 19 March 1994 156 order relation 8 order independent execution 17 78 90 out of order execution 76 overloading 68 page width 50 page width built in predicate 50 panel see graphical
89. an Ait Kaci et al cut will remove choice points much further than expected This behavior of cut should not be relied upon since it probably will change in the compiler Cut should be used in Wild LIFE only to guarantee that a predicate is deterministic without changing its semantics 5 8 2 Disjunctive terms and cut If a goal contains disjunctive terms in its arguments then the choice points for those are created before a rule to prove it is chosen Hence they do not lie in the scope of a cut in the body of the rule Example 5 2 Suppose that the rule p A write A has been asserted The query p X 1 1 2 3 will generate three solutions X 1 and the output 1 then upon backtracking with X 2 and the output 2 and then X 3 and the output 3 Since executing the cut removes alternatives relative to disjunctive terms in the head of the rule the query q X will only generate one solution X 1 and write 1 if the rule q A 1 2 3 write A has been asserted 5 8 8 Negation as failure An interesting application of cut is negation as failure just as in Prolog It is written The symbol was chosen in Prolog because it resembles a tilted version of the mathematical symbol for not provable namely 7 Example 5 3 G G ail The first rule uses the fact that goals use the same data structure as terms It first tries to prove the goal G then if there was a
90. andbook 123 F 4 Passed arguments A passed argument is just an extra feature added to a predicate according to some pred info declaration The use of passed arguments is less interesting since the intro duction of global variables in LIFE pass info ball declares ball as a passed argument There are other optional arguments to this declaration that will be explained later To declare that a predicate uses this argument just add ball to the list in pred info pred info basket ball The expansion will add a ba11 feature to all occurrences of basket If it is not present in the head of the definition it may be initialized if the pass info has a start feature its value will be used to initialize the passed argument Example E 12 pass info kick start quick pass info ball pred_info foot ball kick pred_info basket ball basket foot basket is translated into basket ball gt A foot ball gt A kick gt quick basket ball gt A All rules related to expansion of disjunctions cond cuts and insertion of code still hold The is primitive may be also used with passed arguments Passed arguments may be used in the left hand side of with operators but no operations may be performed on them Their value may be initialized by giving them an argument but not yet using init pass info declaration may also specify an accumulation predicate This predicate can of
91. ator declarations 2l 8 7 5 Files andstreams le 88 System related built ins o 8 8 1 The Wild LIFE system les 8 82 The Unix system o 00 ee ee ee ee es 88 3 Timekeeping ee a e e 8 9 Loading files with term expansion 8 9 4 Defining term expansion clauses 4 8 9 2 Using term expansion when loading files 9 Global variables persistent terms and destructive assignment SET Global variables aod ds di S be 9 2 PersistenttermS gt eed an at oe o BG osx a as Seth er eR f 9 3 Persistent variables 230 so NEAR da ES dest 9 4 Destructive assignment ze ee reed eee Se Rowe NES EUROS 9 4 1 Backtrackable destructive assignment 9 4 2 Nonbacktrackable destructive assignment OS AUOD i sce can nma aree qucd b RAD S Ro ted 9 6 Summary of built ins 3 4 doe xui m EON dux ue Ec XOU es 10 Modules 10 1 Standard modules uu a dhs Rigs eo eg or OR RU a 10 2 Using features Set a ES EE NUN a da 10 3 Overloading ad E oT LE ch ne d aen 10 4 Summary of built ins 30 zu EC AI eR dus vi 33 34 38 41 41 42 43 43 43 45 46 46 47 47 47 48 49 52 53 54 55 55 57 58 58 59 59 11 Rule base management 71 AN ADAN TOS b sd de el ao eee tnc Des 71 11 2 Deleting rules 3 1 xe ore e AS dox EE SOS 72 11 3 Inspectinqg rules 6 ocho ii wr onte Eh XS dert 73 11 4 Func
92. ay check person cleopatra person cleopatra nose gt pretty occupation gt queen julius person julius nose gt big last name gt caesar get along cleopatra julius get along julius cleopatra This explains the following behavior A person kkk Yes A person 1 A f nose gt pretty kkk Yes A cleopatra best friend gt julius nose gt pretty occupation gt queen The constraints attached to cleopatra by inheritance from person are not checked until an attribute becomes present Having appeared as part of the structure of cleopatra as a result of checking cleopatra s constraints julius who is also a person is left unconstrained for the same reason Unfortunately the delay check mechanism is not sufficient to guarantee completeness and convergence in all cases The LIFE compiler will have a consistent handling of recursive sorts that does not need delay check A complete and consistent algorithm to do lazy attribute inheritance has been developed 9 This algorithm takes an attribute constrained in a sort definition into consideration only if it appears in the resolvent March 1994 Digital PRL Wild LIFE Handbook 33 7 3 Constrained sorts as daemons A constraint that is attached to a sort declaration is checked at run time during unification It can be used very effectively as a data driven daemon code whose execution is triggered upon access to an object
93. base in the same order as they will be entered during execution A definite clause is written in the form Head Body where Head is an atomic goal and Body is a non empty sequence of atomic goals An atomic goal is a term whose root sort is defined as a predicate in the program The clause Head succeed may be abbreviated as Head It is called a fact Once defined as a predicate name an identifier may not be declared as a sort However a predicate name may be used as data It behaves as if it were a sort with single parent and single child 5 2 Executing predicates As in Prolog Wild LIFE uses top down left right SLD resolution to execute a query A query or resolvent is a sequence of atomic goals separated by a comma exactly as in the body of a clause Operationally execution of a query proceeds roughly in the following manner The resolvent is set initially to the query and it behaves as a stack of predicate calls 1 If the resolvent is not empty an atomic goal P is popped from the resolvent If the resolvent is empty then the query succeeds The result of the computation is given in the variable bindings 2 The first clause Head Body defining P is chosen If there are no more clauses then the query fails A choice point is created to allow a return to this execution state on backtracking The choice point contains the next clause defining P 3 Head is unified with P and Body is pushed o
94. built in function 47 66 is predicate built in function 47 is_sort built in function 47 ISO standard Prolog operators 53 99 102 syntax 3 keyboard event 129 label 7 11 name space 18 language C 15 C 29 82 CLP R 87 Lisp 26 Login 7 MU Prolog 17 NU Prolog 17 Prolog 1 7 13 14 100 Prolog I 17 Smalltalk 82 lattice 45 least upper bound lub 43 least sorts built in function 45 LIFE language compatibility between compiler and interpreter 1 25 71 75 compatibility with Prolog 97 compiler 1 16 32 71 100 110 Edinburgh syntax 102 history 1 life bugs email address 105 Digital PRL Wild LIFE Handbook life request email address 105 life users mailing list 105 Lisp language 26 list built in sort 9 listing built in predicate 55 load built in predicate 6 49 load exp internal built in 60 load path built in function 49 loading 6 local propagation 19 43 79 87 local_time built in function 58 log built in function 42 logarithm 42 Login language 7 look see graphical interface toolkit 135 lower integer part floor 41 lub built in function 43 mailing list 105 manpage 106 map built in function 24 matching 21 choosing between matching and unifi cation 27 matching and unification example pro gram 27 memoization 31 example program 86 memory management 56 95 141 menu see graphical interface toolkit 134 meta progr
95. course only take two arguments the value to accumulate and the value of the passed argument Example F 13 pass_info hash X Pass acc_pred gt Pass X true pred_info store hash store X Xthash Research Report Draft March 1994 124 Hassan Ait Kaci et al Is translated into store A hash gt B B A true F 5 Common problems and debugging Debugging a program written using the accumulator expander is not an easy task One of the most common mistakes is to forget the expansion of facts or to type instead of To help the programmer a directive may be added to the programs so that warnings are given each time a predicate with an associated pred_info declaration occurs in a non expanded rule This directive is check expansion It only works with expand_load true and for rules ending with a period Example E14 Consider a file with the following declarations acc info acc pred info pred acc pred pred pred pred pred other pred pred A warning will be generated for each of the last three clauses Example F 15 This example illustrates a common problem when mixing DCG predicates with non DCG predicates The problem occurs when the predicates contain other accumulators in addition to the DCG accumulator The problem is solved through judicious use of the with operator Consider the following definition of predicates a and c import accumulators acc
96. d arguments until the first is known At most one of the second and third arguments are evaluated Example 8 2 This example defines an absolute value function using cond March 1994 Digital PRL Wild LIFE Handbook gt absolute V real gt A absolute X kkk Yes A X 1 gt X 34 kk Yes A 34 X 34 e The function and proves P and then returns the i e if either E or P returns more between functions and predicates 35 gt cond V gt 0 V V E P called such that takes an expression E and a goal P It evaluates E value of E as its result No implicit cut is performed than one solution then so will E P This is a bridge Example 8 3 This example shows how the concatenation of two difference lists may be written as a function We use the sort declared as an operator to represent a difference list op 500 xfy gt diffappend A1 A2 B1 B2 gt A1 B2 A2 B1 gt A 1 2 X X B 3 4 Y Y BRANES A 1 2 X X B 3 4 Y Y X Q Y C diffappend A B MON NES A _A 1 2 X X B X Y C A Y X 3 4 Y Y e The function cal1 once P yields t rue ifthe goal P can be proved i e P succeeds and false if it cannot P fails The call call_once P always succeeds This is a bridge between functions and predicates This function returns exactly one solution i e it performs an i
97. d LIFE system assumes that mentioning a class name during execution always creates a fresh instance that is different from all other instances of the class For example gt X 23 Y 23 creates two different instances of the class 23 With the function f defined as gt EA gt 1 the call X Y will not fire since X and Y are different instances To make it fire X and Y must be the same instance In Wild LIFE the only way to do this is to unify them explicitly by doing X Y For example gt X 23 Y 23 X Y write f X Y will write 1 i e the function will fire 4 Sometimes it would be useful to have classes that only have one instance For example it would be nice if all the instances of the class 23 were the same integer 23 i e if the class 23 had a unique instance 23 This is not possible in Wild LIFE 1 0 12 7 Using destructive assignment to calculate term size This section defines the function term_size T which calculates the size of a term The algorithm for calculating the size is a good example of the correct use of destructive assignment It demonstrates the use of both backtrackable and nonbacktrackable destructive assignment and See Section 9 4 for a discussion of these two built ins The size of a term is defined as the number of nodes it contains The algorithm counts the nodes by traversing the term and using backtrackable destructive assignment to mark nodes that have alre
98. d currying provide implicit coroutining An order independent routine is one whose result depends only on the value of its arguments and not on the order in which the arguments were bound relative to when the routine was called If all built in routines called during the execution of a program are order independent then the value of the final result is independent of the order in which the program s functions and predicates are executed The order affects only the execution efficiency See Section 13 3 page 90 for more information on order independence when functions and predicates are used together Since functions can be called before their argument values are known this frees the program mer from having to know what the data dependencies are It provides a powerful search space pruning facility by letting generate and test search be changed into daemon controlled test and generate search A residuated function acts like a daemon it continuously checks whether its arguments are sufficiently instantiated These checks implement a form of data driven synchronization That is the ability of functions to residuate yields a form of concurrent programming Moreover such non declarative heresies as the is 2 predicate in Prolog and the freeze meta predicate in Prolog II are not needed Arithmetic functions in Wild LIFE residuate when necessary Functional residuation provides most of the abilities of MU Prolog s wait declara tions 1
99. d is sign extended for the result This function is not invertible The function sqrt A returns the positive square root of A It is invertible between the domain 0 and the range 0 oo The function exp A returns e where e is the base of the natural logarithms It is invertible between the domain oo oo and the range 0 oo The function log A returns the natural logarithm of A It is the inverse of exp A It is invertible between the domain 0 oo and the range oo f The function sin A returns the sine of the angle A where A is expressed in radians It is invertible between the domain 7 2 7 2 and the range 1 1 The function cos A returns the cosine of the angle A where A is expressed in radians It is invertible between the domain 0 7 and the range 1 1 The function tan A returns the tangent of the angle A where A is expressed in radians It is invertible between the domain 7 2 7 2 and the range oo oo e The function random N int returns a pseudo random integer in the range 0 1 N 1 where N is a positive integer This function residuates if N is not a specific integer The predicate initrandom S real initializes the pseudo random number genera tor with the seed S This is useful when it is necessary to generate the same sequence of pseudo random numbers repeatedly Upon system startup the pseudo random number generator is initialized by calling init
100. d lub create a disjunction if the result is a disjunctive sort a c gt a lt l d gt b lt c b ep d V A glb c d Result is disjunctive sort a b Research Report Draft March 1994 44 Hassan Ait Kaci et al kkk Yes A a First solution epe e Xxx Yes A b Second solution ec Fek No gt A lub a b oe Result is disjunctive sort c d kkk Yes A c First solution eb 3 kkk Yes A d Second solution gt e Xxx No e The predicate subsort A B continuously enforces the relation A lt B It guarantees that the root sort of A is less than or equal to the root sort of B subsort checks the relation when it is called and then attaches itself as a residuation to B Whenever the sort of B is refined it is checked to be not lower than A The function children S returns a list of the declared sorts that are immediately below S in the current sort hierarchy The order of the sorts in the list is unspecified Three built in sorts int real and string have an infinite number of children These are not enumerated i e children int children real int and children string This function does not residuate and hence must be used with caution The function parents S returns a list of the declared sorts that are immediately above S in the current sort hierarchy The order of the sorts in the list is unspecified This function does not residuate and hence must be us
101. dds accumulators to predicates An accumulator provides a means of calculating a value incrementally For exam ple the incremental calculation could be the building of a list Implementing an accumulator consists in adding two arguments to each predicate and chaining the arguments between goals inside each clause This passes the intermediate values around during the calculation The preprocessor can also expand single arguments called passed arguments below which is useful to pass global information to procedures To speed up Wild LIFE s start up time the preprocessor is not loaded by default Any program using it must first import i e load and open the preprocessor module with the command import accumulators Example F1 This example shows how to use the accumulator preprocessor to write a program main N L that takes an input N and generates a list L of integers from 1 to N The accumulator myacc is used to accumulate the elements of the list This example is shown here in its entirety to show how to use the preprocessor and to give a flavor of its the abilities import accumulators Loading File Tools accumulators lf Loading File Tools std expander lf Loading File Tools acc declarations lf gt acc info myacc X In Out acc_pred gt Out X In gt pred info loop myacc loop 0 gt loop N N myacc loop N 1 gt main N L loop N with my
102. develop various compilers simulators analyzers and test generators The Wild LIFE preprocessor jointly developed by Dumant and Van Roy provides much extra functionality over the EDCG preprocessor It is being used in the development of the LIFE compiler F1 Accumulators E1 1 Basic examples and syntax The rules to be expanded are written Head Body Head is like any clause head Body is like any predicate definition body except that some special symbols may appear in predicate places see below accumulation and other features The predicates occurring in the rule are expanded according to the pred info declarations attached to them that tell the preprocessor which arguments have to be added pred info p castor This declaration states that the accumulator castor should be expanded when p is encoun tered The arguments of pred info may also be lists to relate a set of predicates and a set of accumulators 9 If you use named features be careful that there are no conflicts with the features added by the preprocessor These features always start with in or out Example E2 adapted from Van Roy pred info p qdl castor pollux pred info r castor Theclausep p q r s istranslated into p in castor gt A in pollux gt B out castor gt C out pollux gt D March 1994 Digital PRL Wild LIFE Handbook 111 p in castor gt A in pollux gt B out castor gt E out pollux gt
103. dow There are no default values e xRefreshWindow Window Refresh the window There are no default values e xPostScriptWindow Window Filename string Output the window in a PostScript file The default value of Filename is X ps e xGetWindowGeometry Window X0 Y0 Width Height Return the geometry of the window There are no default values e xSetWindowGeometry Window X0 Y0 Width Height Modify the geometry of the window There are no default values e xSetWindowColor Window Color Modify the background color of the window There are no default values e xDestroyWindow Window Destroy the window There are no default values e xRequestColor Window Red Green Blue Color Return a color entry in the color map of the window with the closest RGB The arguments Red Green and Blue must be integers in the range O through 255 There are no default values e xRequestNamedColor Window Name Color Return the color entry in the color map of the window of the named color The argument Name must be a string recognized by the X system a list of these is given through the interactive X command xco e xFreeColor Window Color Free a color allocated by xRequestColor or xRequestNamedColor There are no default values Research Report Draft March 1994 128 Hassan Ait Kaci et al G 3 Primitive drawing operations e xDrawLine Window X0 Y0 X1 Y1 function gt
104. e Clause Grammar DCG 58 110 Definite Clause Grammar example pro gram 120 definition compact sort definition 92 constrained sort 30 function rule gt 17 predicate clause 14 sort attribute 29 sort inheritance 8 delay check built in predicate 31 destructive assignment 62 backtrackable 62 example program 83 nonbacktrackable 62 normal term 62 persistent term 62 use in memory management 95 determinate computation 19 difference 41 difference list 35 110 directed graph 12 directive 6 disjunction 34 disjunctive sort 10 43 disjunctive term 34 interaction with cut 16 redundancy 34 display modules built in predicate 71 display persistent built in predicate 66 division floating point 41 integer 41 dynamic built in predicate 74 Edinburgh syntax 102 email addresses life bugs 105 life request 105 Digital PRL Wild LIFE Handbook life users 105 encapsulated programming example pro gram 81 error 4 54 90 eval built in function 26 evalin built in function 27 event handling 129 event mask 126 example programs accumulator preprocessor 109 appending two lists 27 bagof 64 class 82 concurrent programming 80 communication 80 process 80 synchronization 80 Definite Clause Grammar DCG 120 destructive assignment 83 encapsulated programming 81 Hanoi towers of 85 instance 82 matching and unification 27 memoi
105. e first rule Head gt Expr defining F If no such rule exists then return Returning causes an instant failure to take place Failure causes backtracking to the most recent choice point 2 Match F with Head 3 If F matches Head then the rule fires and the body is evaluated and returned We say F matches Head if to make them equal refinements have to be made only to Head and not to F That is Head is more general than F 4 If F and Head are non unifiable then the rule fails Pick the next rule in the definition of F and go to step 2 If there are no more rules then return 5 If neither step 3 nor step 4 s conditions are true then residuate This suspends the execution of F and returns the temporary result If any of F s arguments are refined then resume execution at step 2 When the function fires the actual result will be unified with the temporary result Therefore the temporary result may be used in further function calls as if it were the actual result This execution mechanism corresponds to a simple formal logical specification 6 Step 3 corresponds to testing whether F implies Head Step 4 corresponds to testing whether F implies the negation of Head Operationally the residuation is attached to each of the residuation variables These are the variables of the calling functional expression on which its comparison with the formal one is still pending More precisely two conditions are guaranteed to h
106. e the sorts true or false The functions perform all possible local propagations For example calling B A and false will cause B to be unified with false and calling B A and true will cause B to be unified with A The functions residuate if a unique result cannot be determined e The function A and B returns the logical and of A and B e The functionA or B returns the logical or of A and B e Thefunction A xor B returns the logical exclusive or of A and B e The function not A returns the logical not of A It returns t rue if A is false and falseisAistrue 8 4 Sorts 8 4 1 Sort calculation These routines provide the means to calculate with sorts in the sort hierarchy and to navigate in the sort hierarchy All functions that return sorts will return them in quoted form so that properties attached to them are not executed e The function g1b A B returns the greatest lower bound of the root sorts of A and B in the current sort hierarchy This function does not residuate and hence must be used with caution See Section 4 1 3 for a full presentation of the glb operation e The function 1ub A B returns the least upper bound of the root sorts of A and B in the current sort hierarchy The lub is the dual operation to the glb This function does not residuate and hence must be used with caution Example 8 15 This example illustrates the glb and lub built in functions It shows that both glb an
107. e variable _A that marks the instance of 7 which occurs in both the lists A and L The function nprimes passes a list of integers to nsift A nprimes 100 k Yes A 2 25 9 011 13 17 19 23 29 291 37 41 43 47 53 99 0L 07 171 73 79 83 89 97 Since the complete list is passed to nprimes see its definition a complete answer can be generated Here is the source code of nsift nprimes N gt nsift integers 2 N Create a stream of integers integers From To gt cond From gt To From integers From 1 To March 1994 Digital PRL Wild LIFE Handbook 81 Remove multiples of P Iter gt lter X In P gt cond X mod P 0 X filter In P filter Im P fil fil 9 Filter out multiples of each element site gt Me nsift P Ns gt Pinsift filter Ns P As an optimization here is a modified version that passes a maximum sift value equal to the square root of the maximum input This is much more efficient than the first version primes N gt sift integers 2 N sqrt N 9 Filter out multiples of each element SEEQDDpje gt sift P Ns Max gt P sift cond P lt Max filter Ns P Ns Max 12 5 Encapsulated programming This example shows how you can create a routine that behaves like a process with encapsu lated data The caller cannot access the routine s local data except through the access functions
108. ead token T S Typed in by the user March 1994 Digital PRL Wild LIFE Handbook 49 Akk Yes S foo T Q e The predicate 1oad A A loads all the definitions in the files A1 A etc in the order they appear This predicate is non strict i e it does not evaluate its arguments Queries appearing in the files being loaded are proved as they are encountered and therefore take into account only definitions that textually occur before them If one file is not found then the remaining files are not loaded an error message is reported and the 1oad fails An error free load always succeeds even if queries in the loaded file fail If a query appearing in a file fails then the remainder of the file following it is loaded anyway A file being loaded may itself contain a load query The outermost load is then momentarily set aside and the nested one is executed in the context reached thus far If no error occurs the outermost 1oad is then resumed in the augmented context Cyclic loadings are ignored i e a file is only loaded once during the scope of a load even if it occurs in more than one load query e The function 1oad path may be defined by the user to return a directory name or a disjunctive term containing directory names A directory name is given as a string e g usr lib include is a valid directory name During a load or import command the current directory is searched first followed by the directories returned
109. ed FG Menus e VOD A Sew sb EVE FAAS Sliders Cs aod o ds UNS de rid ais FAAS HOOKS gt te celts Soo Rt ee Pep E Ce CIS efc ene De PERPE eas HAT LooktypesS ovo bg RE pd ES X a ey H 42 Inheritanceoflooks les H 43 Colorsandfonts a H 5 The hierarchy of graphical interface objects ELO Sereen oDIBOIS raus ao RC Del USC RE OUS DN QU 106 109 110 110 111 112 115 115 116 120 120 121 121 123 124 125 126 126 126 128 The C LIFE interface 140 1 1 DESCUPION ai a prb SEO ra e dtl 140 12 A simple example llle 140 1 3 Summary of functions and prototypes 140 4 Memory management mo ede ues 141 5 An exhaustive example o 141 References 145 Wild LIFE Handbook 1 l l ment ne pr existe pas l ensemble il n est ni plus imm diat ni plus ancien ce ne sont pas les l ments qui d terminent l ensemble mais l ensemble qui d termine les l ments i Georces Perec La vie mode d emploi 1 Introduction LIFE is a programming language originally conceived by Hassan Ait Kaci and his colleagues at MCC in Austin Texas 4 5 3 It is a synthesis of three different programming paradigms logic programming functional programming and object oriented programming LIFE is a declarative logic based language that can be seen as a constraint language It derives its syntax and resolution method from Pro
110. ed to be tagging exactly as if it had been written x 8 9 The terms s X X t and s X t X are identical i e the tagging construct is simply a syntactic device used to represent sharing and cycles in the textual representation of a term It is possible to write any directed graph structure as linear text using variables and tags For example when Wild LIFE sees X foo bar gt X itcreates a single cyclic structure with name X The tagging construct is not exclusively reserved to be used in the form X t Other sensible forms are t X which is equivalent to X t and more generally X1 X2 Xp which is equivalent to X Xo X2 Xa X n 1 Xn for n variables X through X At most one of the X may be a term whose value is different from Example 4 4 Here are four examples of the use of tags e father name N string son boy name N represents a father who has a son such that the son shares the same name as his father The tag N represents the name e A A is a list whose first and second elements are identical e L int int int L is a cyclic list of length three whose three elements are integers e write A happy A person prints the output person then go on to prove the goal happy person because the tag A was bound to person globally for the whole query at parse time This query is equivalent in all respects to write A person happy A 4 4 Unification Unifyi
111. ed with caution Example 8 16 This example illustrates the parents and children built in functions gt a la gt a lt l d gt b lt c gt b lt d March 1994 Digital PRL Wild LIFE Handbook X parents a Y children c we YES X c d Y a b 1 gt kkk No gt X parents c Y children a KkK Yes X Y 45 e The function least_sorts returns a list of the sorts that are immediately above in the current sort hierarchy The order of the sorts in the list is unspecified 8 4 2 Sort comparison These functions perform sort comparisons and return true or false The comparisons are done with the root sorts of the arguments Because the sort hierarchy is a mathematical lattice sort comparisons do not satisfy trichotomy i e it is possible for none of A B A B and A gt B to be true As a result there are more than six possible comparisons Twelve of the 30 possible comparisons have been given a name The names of all sort comparisons start with a The names are consistent with the names of the arithmetic comparisons except for sort equality and nonequality which use and instead of and 1 These functions do not residuate and hence must be used with caution They can be made order independent by wrapping them in another function definition e The function A gt B returns t rue if A is greater than B in the sort hierarchy
112. en 6 Functions 6 Defining functions soci Taea doe do eo e RE aces 6 2 Executing functions 3 92 as Russ XONWIX E e Ee 6 37 Matehing uoo he dedo oh rele DOR ea Yo e orale pub OUMINI Tas Ly dn ecu Lo vei gu ALIVE peret 65 Quote aldigyal z cede acit QR e ue dde pe de s ate Re deo Badia 6 6 Choosing between matching and unification 7 Constrained sorts 7 4 Defining constrained sorts o 75 11 Sortaltrbules 5 vu ae A eee ees 71 2 Constrainedsorts e 7 2 Executing constrained sorts m ge Y Se e X CR UN OE Se X9 Ta 7 3 Constrained sorts asdaemons 04 8 Basic built in routines UA Control TOW udo tae deae A Lote at d A 8 2 a manipulation Ce trae e EXC oe eee og CUR NUA OE RUR E Bus ABIIBIIO qr to geo p TL eene a bee Qe dabat 8 3 1 Arithmetic calculation ees 8 3 2 Arithmetic comparison e eee eee 8 3 3 Boolean arithmetic o o ee Bite SONS Us a 37 o is eee ae e e dis 8 4 1 Sortcalculation o o e 8 4 2 Sortcomparison o 9 5 SUINOS gt ed iets a e LA 8 5 1 String calc lation lt o e aa o oo o 8 5 2 String comparison o o 30 Typechecking eres tdeo e e de e Cy take dede in da O A os A uEEECA X ee ee ee a amp v RHeadig s boxe ooh wt dt her RE tue Eu 8 727 Writing xs ur sea ee E ee A 8 7 3 Parsing a string v so oe EA x tuU ESECY wes 8 7 4 Oper
113. en the unification yields a term that describes the intersection The records in the intersection have all the fields of both sets This explains why the attributes of the unifier term form the union of the ones of the two parent terms Here union means the set of attributes that appear in at least one of the two terms The attribute for a common label has a 4 term describing the intersection of the two corresponding terms 4 4 1 A step by step comparison with Prolog unification Unification of terms generalizes unification of Prolog terms This is progressively illus trated in the following cases 1 Unifying two terms with same root sorts and arguments e g X foo s1 5 and Y oo ti tn is done as in Prolog 2 Unifying X oo s sn and Y bar ti t leads to failure exactly as in Prolog if oo and bar are incompatible in the sort hierarchy This means that the user has not declared any subsort which is below both oo and bar Whether n m or n m has no effect on success or failure 3 Unifying two terms which have exactly the same set of labels and the same sort X foo h Hiss ly gt Sn and Y foo l gt ti ln gt tn is a slight generalization of case 1 there the numeric features l 1 n are left implicit The unification proceeds in direct extension of case 1 4 Unifying two terms which have the same set of labels and two compatible sorts s1 a
114. eport Draft 157 cons 9 false 9 int 9 list 9 nil 9 real 9 string 9 true 9 calculation children 44 greatest lower bound glb 43 least upper bound lub 43 least sorts 45 parents 44 subsort 44 class 8 82 comparison comparable gt lt 45 equal 45 greater than gt 45 greater than or equal gt 45 less than lt 45 less than or equal 2 45 not comparable 1 gt lt 46 not equal 1 46 not greater than gt 45 not greater than or equal gt 45 not less than lt 45 not less than or equal lt 45 consistency 9 constrained 30 76 declared sort 14 29 47 92 94 definition attribute 29 inheritance 8 disjunctive sort 10 43 encoding 94 extending built in sorts 10 greatest lower bound glb 10 94 hierarchy 10 incompatibility 10 inheritance 8 name space 18 60 66 navigating the hierarchy 43 March 1994 158 property 29 recursive 31 syntax 8 29 top 9 type 8 undeclared 29 sound negation 16 sqrt built in function 42 square root 42 standard order comparisons 99 static built in predicate 74 statistics built in predicate 56 step built in predicate 56 str2psi built in function 46 strcon built in function 46 string calculation concatenation strcon 46 conversion from term psi2str 46 conversion from ASCII chr 46 conversion to term str2psi 46 conversion to ASCII asc 46 extrac
115. er X Z father Z Y TARY Yes We try a query gt grandfather A B y xk xk Yes A john B michael 3 3 Incremental query extension Upon success of a query the user is offered the possibility of extending it using the resulting context This can be continued to any level of nesting The query level is printed in the form of a numbered and indented prompt At the prompt the user can take one of the following actions e Type a goal followed by to extend the query e Type CR to abandon the last query increment and go back to the previous level e Type to force backtracking and look for another answer e Typeaperiod to pop up to the top level prompt from any depth March 1994 Digital PRL Wild LIFE Handbook e Make an assertion that uses the variable binding context by typing a declaration followed by a period Example 3 3 Continuing on the previous example now enquiring about A s son C where A john 1 father A C EXE YES A john B michael C harry Let us check whether an alternative solution exists that is compatible with the context of the previous level by forcing backtracking muc X kkk Yes A john B michael C charles We are again at query level 2 but one that is independent from the previous level 2 Let us again force backtracking 2 kk xk No A john B michael This query extension fails and brings the level back to 1
116. ers and the symbols int and real with the order relations n int for all integers n r real for all non integral floating point numbers r and int real For example 0 5 and 3 0 are subsorts of int and thus of real 2 5 and 26 77 are subsorts of real but not of int e list empty list which may be written nil and cons the list constructor with the order relations list andcons list Lists may be written with the same syntax as Prolog e g a b c a b c a b c al bl el 1 e All strings s and the symbol string with the order relations s string Specific strings appear within double quotes asin this is a string e bool true and false with the order relations true bool and false bool Because T is not a standard ASCII character we need an ASCII symbol to stand for it Besides resembling a looped around a that could stand for anything the symbol has a shape that is reminiscent of an embryo a perfect ideogram to denote the most primeval sort in LIFE 7 As opposed to other non numeric sorts strings are non interned symbols i e they are not put in the symbol table Research Report Draft March 1994 10 Hassan Ait Kaci et al e built in a sort which is a supersort of all built in sorts with the order relations list built in string built in real built in and bool p use ean To summarize the system contains the following predefined declarations
117. esult A B is called a type disjunction or a disjunctive term A singleton disjunctive term t is equivalent to t An empty disjunctive term is equivalent to the bottom sort and causes an immediate failure Example 8 1 This example shows how disjunctive terms result in more compact code e A 1 2 3 4 is equivalent to A 1 A 2 A 3 A 4 e p a b c is equivalent to asserting p a p b p c Unifying U 1 2 3 4 5 with V int 2 4 6 8 results in the disjunctive term U V 1 2 2 3 4 4 5 In theory the above ought to be U V 1 2 3 4 5 rather than U V 1 2 2 3 4 4 5 since a unifier does not contain redundant in formation To perform this correctly unification of disjunctive terms should remove any term in the resulting disjunction that is subsumed by another disjunct Since this is costly Wild LIFE does not perform the complete operation oy The predicate pronounced cut removes all choice points up to and including the choice point that was created when entering the predicate in which the cut occurs See Section 5 3 for a discussion of cut The function cond B T F isaconditional that returns T or F depending on the result of B The conditional returns T if B evaluates to true and F if B evaluates to false If B is a predicate then B is executed and the conditional returns T if B succeeds and F if B fails The conditional residuates otherwise It does not evaluate its second or thir
118. esult of E If there is an error in any A then none of the A are declared This predicate should be used only as a declaration i e in a query and not in a definition The predicate persistent A A2 declares Aj A etc as persistent variables This predicate is non strict i e it does not evaluate its arguments Each argument A must be an uninterpreted identifier If there is an error in any A then none of the A are declared This predicate should be used only as a declaration i e in a query and not in a definition The predicates A B and A B implement backtrackable and nonbacktrackable de structive assignment The function is_persistent X returns t rue if X is a persistent term and false 1f X 1s a normal term i e X is backtrackable The predicate display persistent X is used to enter and exit a mode in which persistent terms are displayed differently from normal terms This built in is intended for debugging purposes If X is false then persistent terms are displayed in the same manner as normal terms This is the default If X is true then persistent terms are preceded by a dollar sign If X does not exist then the display mode is toggled 10 Modules The module system creates an entirely separate set of symbols for each module By symbol we mean any identifier i e a predicate function or sort or feature name The symbol name space is partitioned into three subspaces for predicate fu
119. f objects which themselves may be represented as records Hence the term may be construed as a record type A term with given attributes describes records with at least the fields specified by the attributes but possibly others The values in the fields are themselves records which are described by 4 terms Furthermore the records must satisfy the coreferences expressed by the tags of the 4 term 4 1 Sorts Sorts are the syntactic entities attached to the root of every term In this sense they take over the role of type names in C and functors in Prolog Sorts by themselves constitute the most basic 1p terms The sort attached to the root of a term is called its principal sort or root sort Any symbol that is introduced in the text of a program or query is considered a sort unless 1t is declared otherwise or it is a label A sort may be any integer or floating point number or character sequence The character sequence must be surrounded by single quotes if it does not start with a lower case letter or 1f it contains non alphanumeric characters other than underscore A character sequence surrounded by double quotes is also allowed it is an explicit string No conceptual difference is made between values and sorts This means that for example the value 1 is specified by the sort 1 The fact that this is an integer value is specified by saying that 1 is a subsort of the sort of all integers which is written int 4 1 1 Defining sort in
120. g This section presents an algorithm for PERT scheduling that illustrates the advantages of out of order execution and of object orientation The program calls the functions that calculate the scheduling information before their arguments are known The functions are attached to the declared sort task providing for a clean data encapsulation PERT Program Evaluation and Review Technique is a methodology for planning big projects In particular it is used to schedule subtasks that comprise a bigger task For example the big task of building a house can be divided up into many smaller tasks architectural design buying a plot of land contracting for the building the plumbing the electricity interior decorating and so forth Each of these subtasks is dependent on a given set of other subtasks to start Each of the subtasks has a duration An important problem is to find the earliest and latest starting times of each task such that the big task is completed as soon as possible If there is no limit on the number of tasks that may be done in parallel then this problem has a linear time solution A Wild LIFE program to solve this problem can be written as follows This program is one of the examples provided with the release First define a sort task that represents the information relevant to a task A task duration gt D real earlyStart gt earlyCalc R March 1994 Digital PRL Wild LIFE Handbook 77 lateStart gt 1e500 real
121. g will not see the clause March 1994 Digital PRL Wild LIFE Handbook 73 gt p write aha retract p B retract p C gt p write boo gt p aha kkk Yes A There are no further solutions to p kKkK No 11 3 Inspecting rules The predicate clause C unifies C with the first clause in the program that is unifiable with C On backtracking it will be unified with all successive clauses that are unifiable with C Example 11 4 p EEN Yes gt p 2 write hello KKK Yes gt clause A p B KkK Yes A p 1 B succeed eM KKK Yes A p 2 B write hello cep kKkK No 11 4 Function definitions It is possible to use the above predicates assert retract and clause with function declarations The argument is of the form Head Result Again you have to be careful with choice points and new definitions will not modify previously existing 4 terms which had already been evaluated Example 11 5 Research Report Draft March 1994 74 Hassan Ait Kaci et al gt A f assert f gt sdsd B f Xxx Yes A f B f The fact that predicates and functions are represented with terms makes it easy to write meta interpreters But the differences between various possible implementations of assert and retract are just a reminder of the inherent pitfalls of using self modifying code This code is very difficult to debug and is compiled much less efficiently If y
122. h sorts allow a similar kind of filtering 2 A DECstation 3100 has speed similar to a SPARCstation 1 See Section 12 11 Research Report Draft March 1994 80 Hassan Ait Kaci et al 12 4 Concurrent programming Here is a little program that shows how a committed choice programming style can be imitated in Wild LIFE The program is transliterated from an FCP Flat Concurrent Prolog example in Shapiro s survey article on concurrent logic programming 18 LIFE s function suspension mechanism i e residuation is used to communicate between functions In the terminology of concurrency a recursive function acts like a process Com munication between processes is done through unification of shared variables Synchronization is done through residuation Task switching is completely data driven and hence the scheduling policy is non fair Here is a sample session gt A nsift 2 3 4 5 L Yes BS gop Ole ew Ue 1l gt L 6 7 8 9 L2 oe The system waits on L Refining L resumes the computation oe oe Yes A 2 3 5 _A 7 L 6 8 9 L2 L2 A Now it waits on L2 2 O 2 gt 12 107 1712 1337 7 Refining L2 resumes the computation EAE YES A C 2 3 5 4 AT T7 B 11 6 A3 G8 L 6 _A 8 9 L2 L2 1T0 B 12 C L3 L3 Q Now it is waiting on L3 The list A contains only prime numbers Shared objects are given system generated names e g th
123. he bit vectors is irrelevant to the programmer but for the curious the query print codes will show them The upshot of this is that there is an encoding phase which can be likened to compilation This is invisible to the user A constant without any definitions i e an uninterpreted identifier is considered to be alone in its class i e it can only be unified with or itself It is not encoded 13 6 Printing convention Wild LIFE uses a systematic convention for printing the arguments in the body of a term First the arguments of numeric positions are printed using the natural number ordering then the arguments corresponding to word attributes using the lexicographic ordering on the attribute labels All symbolic attribute labels are printed explicitly A numeric position is printed only if necessary Namely position 1 is never printed explicitly and any other position is printed explicitly only if a lower position is missing Example 13 5 gt X f 2 gt t2 a gt ta t1 4 gt t4 b gt tb ab gt tab kk x Yes X t1 t2 4 gt t4 a gt ta ab gt tab b gt tb Other important points if you are interested in parsing input are that e parentheses are removed from expressions wherever they are unnecessary e a op b where op is an infix operator is syntactic sugar for op 1 gt a 2 gt b e op a where op is a prefix operator is syntactic sugar for op 1 gt a For example execute the query import
124. he box DX and DY are integers giving the dimensions of the box Boxes may contain other boxes the mother feature of a box points to the box that contains it if any The border feature is the width of reserved space on each side of a box It has a default value d_border The following sections list the placement constraints on boxes that are implemented in the toolkit These constraints may be accumulated and imposed in any order The local constraint propagation of Wild LIFE guarantees that if the constraints are consistent and enough information exists to determine a placing 1t will be determined If the constraints are inconsistent then they will fail and cause backtracking H 2 1 Boxes used as padding Some boxes are only used to reserve space between objects e h box W isa function that returns a box of width W e v box H isa function that returns a box of height H e null box isa box of zero size It is the sort null box box null box width gt 0 height gt 0 The values inh box W and v box H may be negative H 2 2 Positioning e Relative positioning The toolkit offers a number of primitives to place boxes l_above c above r above l below c below r below t left of c_left_of b_left_of t right of c right of b_right of The letter prefixes have the following meaning 1 stands for left r for right t for top b for bottom and c for center Each of these primitives is a function returning the sma
125. heritance Sorts are put in a hierarchy by specifying a partial order relation between sorts The order relation is declared by means of sort inheritance definitions which are written as s1 s2 This declaration can be read as s1 is a s2 or s1 isasubsortof s2 Thetexts1 s2 is the programmer equivalent of the mathematical notation s lt 1s2 Through this declaration s1 inherits all properties of s2 A sort may occur in several inheritance definitions if it has more than one direct relative i e parent or child Sorts denote sets and the partial order between them amounts to the subset relation Hence a sort may be viewed as a type of records and the partial order as type inheritance We will later see in Section 7 page 29 that we can declare a definition for a sort it then becomes a class in the object oriented sense The subsorts of a sort inherit all the properties defined for the parent sort Different sorts may have common subsorts thus allowing multiple inheritance Example 4 2 Let us declare a small hierarchy that describes the relationships between trucks and vehicles We assume that any truck is also a vehicle and that any property pertaining to vehicles also applies to trucks That is trucks inherit all properties of vehicles This is specified in Wild LIFE by typing truck vehicle Subsequently Wild LIFE s unification will take the inheritance information into account 9 truck vehicle A truc
126. hree calls op X Y Z op precedence gt X kind gt Y functor gt Z andop X Y Z precedence gt X kind gt Y functor gt Z areequivalent Because the head is a i term any mixed or incomplete list of arguments may be specified even op precedence gt X 3 gt Z In addition unlike Prolog s op which is a declara tion Wild LIFE s op can be dually and indifferently used in both assertion and query mode Thus op precedence gt X kind gt xfy functor gt Z will successively bind X and Y to all pairs of precedence weights and functor symbols of kind xfy This is quite handy to define new operators precedences relatively to known ones as functions or constrained by the defined values all without being aware of their actual specific and often arbitrary values 8 75 Files and streams File I O operations in Wild LIFE are reduced to a simple form files may be opened in either read or write mode and closed It is possible to open several files for input and or output with open in and open out and to switch between them with set input and set output For consistency all trace messages are always output to stdout all errors and warnings to stderr and all program output to the stream selected by the user The default initial selections are stdin for input and stdout for output The following built in predicates provide file I O operations e The predicate exists file F succeeds if and only if the file
127. ild LIFE Handbook 41 e The function X Y identity yields true if the arguments X and Y are the same term i e if they have been explicitly unified together Otherwise it returns false This function does not residuate and hence must be used with caution e The function X Y yields true if the arguments X and Y are different terms i e if they have not been unified together Otherwise it returns false This function does not residuate and hence must be used with caution 8 3 Arithmetic 8 3 1 Arithmetic calculation These functions coerce the sort of their arguments and results to real Many of the functions can be inverted A local inversion is performed if the inversion is deterministic i e if only one solution is possible For example executing the goal A A 5 binds A to 0 The bit manipulation functions A NB A B A gt gt B A B A are not invertible Executing the goal 25 A A residuates since there are two solutions 5 and 5 Applying a function followed by its inverse may not result in an identical value because of floating point roundoff error e The function A B returns the sum of A and B The function A B returns the difference of A and B The function may also be called with a single argument as A in which case it returns the negative of A The function does not curry in this case The symbol is defined as a unary operator which makes parentheses unnecessary when called with a sing
128. info acc gt pred info a b c d acc gt c r S t Non DCG predicate gt a b c d DCG predicate The expansion of a adds the two DCG arguments to b c and d March 1994 Digital PRL Wild LIFE Handbook 125 gt listing a al in acc gt A in dog gt _B out acc gt C out dog gt _D b in acc gt A in deg gt _B out acc gt _E out_dcg gt EF cl in acc gt E in dog gt _F out acc gt _G out_dcg gt _H d in acc gt _G in deg gt _H out acc gt _C out_dcg gt D The problem is that c is not a DCG predicate hence it does not know what to do with the two DCG arguments The fix is to insulate c from the DCG accumulator by using with gt a b c with deg d Correct definition gt listing a al in acc gt A in dog gt _B out acc gt C out dog gt _D b in acc gt A in_dcg gt B out acc gt _E out_dcg gt EF c in acc gt _E in dcg gt c is bypassed out acc gt _G out_dcg gt 8 d in acc gt _G in deg gt _F out acc gt C out deg gt D The DCG arguments are now correctly chained between b and d bypassing c F6 Term expansion The preprocessor includes term expansion clauses for gt pred info acc info and pass info This means that if you execute expand load true then all rules loaded from files may be written as definitions instead of as querie
129. interface toolkit 133 parents built in function 44 parse built in function 52 parser 105 curried expression 24 partial evaluation 97 partial order 8 pass info declaration 123 passed argument 123 passive constraint 78 persistent built in predicate 66 persistent term 61 62 example program 83 persistent variable 61 quoting 65 PERT scheduling example program 76 position function 90 predicate 90 pred info declaration 110 predefined sort hierarchy 10 predicate 14 definition 14 name space 18 60 66 operational semantics 14 position 18 90 unification 12 use as sort 20 use of cut 15 preprocessor see accumulator 109 pretty write built in predicate 49 pretty writeq 49 prime numbers example program 75 principal sort 8 print depth 50 print codes built in predicate 94 print depth built in predicate 50 March 1994 Hassan Ait Kaci et al private built in predicate 70 private feature built in predicate 70 product 41 profiler tool in version 1 0 105 program file 6 project 38 projection 64 Prolog II language 17 Prolog language 1 7 13 14 100 compatibility with LIFE 97 Edinburgh syntax 102 is 2 built in 17 ISO standard operators 53 99 102 ISO standard syntax 3 standard order comparisons 99 univ built in 2 99 pseudo random numbers 42 psi term see 4 term 7 psi2str built in function 46 public built in predicate 70 put buil
130. ion equality constraint Arithmetic functions in Wild LIFE do local propagation That is they handle all cases where the value of one or more arguments can be determined uniquely from the others For example gt 23 10 X Yes X 13 Another example gt A A C kk x Yes A real C 0 Research Report Draft March 1994 88 Hassan Ait Kaci et al This example residuates i e suspends gt A A B k Yes A real B real note the tildes since there are two solutions A 0 or B 1 For real numbers CLP R does more in addition to local propagation it does global con straint solving with linear equalities and linear inequalities on real numbers using incremental Gaussian elimination and incremental Simplex based on Fourier elimination On the other hand Wild LIFE does local constraint solving on terms which are rooted graphs that live in a hierarchy So for example Wild LIFE can check structural constraints like graph subsumption which CLP R cannot Example 12 1 This example illustrates the use of graph subsumption as a constraint gt X s a gt t b gt X gt true Define a function kkk Yes gt A f G Check if graph G implies the cyclic graph X s a gt t b gt X KKK Yes A G 1 G s a gt t b gt X oe Make G an acyclic graph It doesn t fire yet oe EEN YES A G s a gt t b gt X X Q 2 gt G X Adding
131. isplay modules true KKK Yes P secret prison door gt user guarded secret entrance gt secret tunnel Research Report Draft March 1994 68 Hassan Ait Kaci et al 1 F features P ARE NES F user door P secret prison door gt user guarded secret entrance gt secret tunnel The feature entrance is private to secret and so when in module user the function features only sees the door This is true for all built ins that manipulate features 10 3 Overloading The module system allows symbols to be overloaded This works because modules allow the distinction to be made between the new symbol and the old typically built in definition Example 10 2 Wild_Life Interpreter Version 1 0 Copyright C 1991 93 DEC Paris Research Laboratory No customizing file loaded gt private Warning local definition of overrides syntax gt op X Y syntax op X Y A list B list append A B gt A string B string gt strcon A B gt A real B real gt A syntax B MAA PYES gt write la by elt tlae xl 017 a b c d e f KKK Yes gt write abc def n1 abcdef kkk Yes gt write 3 4 n1 gt xk xk Yes This works but is only usable from within a single module If you try to export the overloaded definition of a clash results between syntax and the exported March 1994 Digital PRL Wild LIF
132. it runs the queens program The program is in the file demo c here is a listing Example C program calling Wild LIFE finclude Source c life h main argc argv int argc char argvl int ans PsiTerm a PsiTerm sum char features int i double value int ok Initialize Wild LIFE WFInit argc argv Currently doesn t use the arguments Submit a query N042 is a quote sign ans WF Input write N042Welcome to Wild LIFE 042 n1 Deal with Wild LIFE response switch ans case WEno printf WFInput failed Win break case WFyes March 1994 Digital PRL Wild LIFE Handbook 143 printf WFInput succeeded Wn break case WFmore printf WFInput succeeded and there may be more answers Mn break This query fails and so prints an error message WFProve true false Solve a simple constraint WFProve A B C7 WFProve B 1 WFProve A 5 ue DE Me WFProve Backtrack over 4 solutions HE rove n TITO de ID REED ug WFProve WEProve ngos WFProve WFProve No more at this point Backtrack over only the first 2 solutions WFProve A 6 7 8 write A nl WFProve WFProve Return to top level Build a psi term and query it WFProve A message N042threecfourN042 equals 5344 write A n1
133. k xButton3MotionMask Button4MotionMask xButton5MotionMask xButtonMotionMask KeymapStateMask xExposureMask xVisibilityChangeMask xStructureNotifyMask xResizeRedirectMask xSubstructureNotifyMask xSubstructureRedirectMask xFocusChangeMask xPropertyChangeMask xColormapChangeMask xOwnerGrabButtonMask tU X x XX XX G 2 Primitive control operations e xOpenConnection Display Screen string Open an X connection on the specified screen The default value of Screen is the contents of the environment variable DISPLAY The field containing this value may be omitted e xCloseConnection Display Close the connection opened by a xOpenConnection e xCreateWindow Display X Y Width Height Window color gt Color windowtitle gt WindowTitle icontitle gt IconTitle eventmask gt EventMask Open a window on the specified display at X Y with the given width and height and with the given background color EventMask contains March 1994 Digital PRL Wild LIFE Handbook 127 a bitwise or of the accepted events The default values are Color xWhite WindowTitle Life IconTitle Life eventmask xKeyPressMask xButtonPressMask xExposureMask where is the bitwise or function The fields containing these values may be omitted e xShowWindow Window Show the window There are no default values e xHideWindow Window Hide the win
134. k is a vehicle gt This must not be confused with the predicate subsort that tests whethertwo sorts are related see Section 8 4 March 1994 Digital PRL Wild LIFE Handbook 9 kkk Yes gt mobile vehicle oe A vehicle is mobile kkk Yes gt useful truck oe A truck is useful XX NES mobile X useful X oe What is mobile and useful Yes X truck A cycle within the hierarchy such as a b b c oc lt a is reported as an error This enforces consistency of the sort ordering as itis specified by the user Consistency checking becomes more complex when properties are attached to sorts in Section 7 Wild LIFE does not check consistency of properties attached to sorts 4 1 2 Built in sorts At the summit of the hierarchy of sorts there is a greatest sort denoted by pronounced top That is between any sort s and the sort T the order relation s T is always specified In Wild LIFE the symbol is used to represent T Likewise at the base of this hierarchy we find the sort L pronounced bottom That is between any sort s and the sort the order relation s is always specified In Wild LIFE the symbol is used to represent 1 From now on we will write and to denote T and L The sort denotes the set of all records The sort denotes the empty set Besides and the other built in sorts available to the user are e All integers floating point numb
135. l make execution resume from where it was interrupted a will cause it to abort execution and return to top level h will make Wild March 1994 Digital PRL Wild LIFE Handbook 7 LIFE print out a reminder of the meaning of these abbreviations t will turn trace mode on s resp CR will turn single stepping on Both tracing and single stepping are automatically turned off by a and c 4 The basic data structure v terms In Just as Prolog is based on first order Herbrand terms LIFE is based on terms order to compare the two one can say that terms are to Prolog terms what flexible records are to static arrays Namely instead of selecting subterms just by numeric positions we can use labels i e symbolic keywords also called features and instead of fixing the number of subterms beforehand we can add more subterms to a term at any time even by user input at run time We call a subterm together with its label an attribute of the p term A label may be any natural number or any symbol The symbol must be single quoted if it does not start with a lower case letter or if it contains non alphanumeric characters other than underscore Furthermore instead of Prolog s mutually incompatible functor symbols we use sort symbols that the programmer puts into a hierarchy expressing hereby their relation i e their degree of compatibility Finally in order to express coreferences aliasing not just between leaves of the te
136. l through to the following clauses just like a standard predicate call Execution is identical to that of a standard predicate except that matching is used instead of unification to see whether a clause is entered See Section 12 10 for an illustration of the use of implies in the graphical interface toolkit Example 8 9 This example illustrates implies gt p X int write X X nl k YES gt X l int real implies p X fail X 1 X int KkK No YP term manipulation These functions are useful for explicitly building and taking apart 4 terms The predicate A B unifies the two 1 terms A and B It succeeds if the terms are unifiable and fails if they are not Writing X s Y s amounts to the same as writing the predicate call eq X s Y s if the predicate eq is declared by the clause eq U U The function A amp B unifies the two terms A and B It returns the unified value It succeeds if the terms are unifiable and fails if they are not Writing X s amp Y s amounts to the same as writing the functional expression eqfun X s Y s if the function eqfun is declared by the rule eqfun U V U U V The function A F project selects feature F of term A F may be passed as a string an integer or a sort This generalizes record field selection of imperative languages If the field does not exist then it is created If F is then the function residuates until the field
137. le argument The function A B returns the product of A and B The function A B returns A divided by B This is a floating point division e The function A B returns the integer part of A divided by B i e the integer between 0 and A B that is closest to A B The arguments A and B must be integers e The function floor A returns the largest integer less than or equal to A The function ceiling A returns the smallest integer greater than or equal to A The function A B returns the bitwise and of A and B The arguments A and B must be integers The low word 32 bits of the result is valid This function is not invertible The function A B returns the bitwise or of A and B The arguments A and B must be integers The low word 32 bits of the result is valid This function is not invertible e The function A gt gt B returns the arithmetic signed right shift of A by B places The arguments A and B must be integers The low word 32 bits of the result is valid This function is not invertible The function A B returns the arithmetic signed left shift of A by B places The arguments A and B must be integers The low word 32 bits of the result is valid This function is not invertible Research Report Draft March 1994 42 Hassan Ait Kaci et al The function A returns the bitwise negation of A The argument A must be an integer The bitwise negation of the low word of A 32 bits is taken an
138. le assignment to persistent variables can be used to keep information while backtracking For example we could compute 4 with the following program persistent result foo3 0 result result l foo3 X X gt Qy foo3 R X 1 foo3 R foo3 R foo3 R fail Succeed dus power3 N result 0 foo3 N X result write X Research Report Draft March 1994 96 Hassan Ait Kaci et al Calling power3 8 writes 65536 The remaining garbage collections can be avoided if is used less often The following program uses four times less often than the previous one and runs about 45 faster persistent result foo4 0 Counter X X 1 foo4 N 0 Y N 0 foo4 R N 1 3 result X1 foo4 R 3 X1 X2 foo4 R 3 X2 X3 foo4 R 3 X3 X4 result lt lt X4 fail Y result foo4 N P X Y N 0 foo4 R N 1 C P 1 X X1 foo4 R C X1 X2 foo4 R C X2 X3 foo4 R C X3 Y power4 N result lt lt 0 foo4 N _ 0 X write X This technique can always be used when the program s resultis given through nonbacktrackable operations such as writing drawing or asserting 14 2 Residuation Residuation is a very useful tool to write efficient programs when a kind of coroutining behavior is expected In many generate and test programs such as eight queens residuation enables the programmer to put the test predicates before the generation
139. lized The with operator has been designed to let other sets of accumulators play the same role An expansion is characterized by two concepts e Its scope the set of terms affected by the expansion e Its context the set of accumulators that will be linked together during the expansion Until now the scope of an expansion was always the whole clause and its context the set of accumulators expanded in the head With enables the programmer to define the scope and the context of an expansion With is defined as an infix operator of precedence 800 and kind xfy i e it binds tighter than the control operators used in clauses and so on but looser than functional expressions Example E9 Let us consider the following program pred info head bodyl body2 acc1 pred info bodyl body2 body3 acc2 head bodyl body2 body3 with acc2 The initial scope of the expansion is the whole clause with context acc1 This means that acc1 will be expanded and linked in head body1 body2 With defines a new context acc2 with scope body2 body3 this means that acc2 will be expanded and linked in body2 and body3 but not linked with the arguments of body1 since body1 doesn t belong to the scope of this expansion This may be represented this way The scopes are represented by the big rectangles with the corresponding contexts on their upper edge Each pair of expanded arguments is represented by a term acc whe
140. llest box containing its two arguments for instance Box1 1l above Box2 returns the smallest box containing Box1 and Box2 such that Boxl is above Box2 and their left sides are aligned These primitives will set and try to resolve the placement constraints Research Report Draft March 1994 132 Hassan Ait Kaci et al e Containment The toolkit offers two primitives to express that one box contains another contains containing Syntax Boxl contains Box2 Box Boxl containing Box2 Both of these primitives express the same containment constraint The difference is that contains isa predicate and containing a function If no size is specified for Box1 it will be given the same size as that of Box2 The function call containing returns the containing box in this case Box1 If Box1 has a border feature worth Border in pixels it will be used to reserve a space of that width around the box In this case Box1 will be larger than Box2 Refined positioning There are also some primitives that set finer constraints ll aligned lr aligned lc aligned rr aligned rc aligned tt aligned tb aligned tc aligned bb aligned bc aligned cc v aligned cc h aligned These are predicates The first letter of the predicate name applies to the first argument the second to the second argument As before 1 stands for left r for right t for top b for bottom and c for center
141. log Except for differences in built ins Prolog programs can run unaltered in LIFE if they follow the syntactic convention that each predicate and functor symbol is used with one arity only However the addition of functions approximation structures 1 terms and inheritance greatly enriches the language and allows one to formulate efficient programs more easily more concisely and in our opinion more naturally 7 8 Wild LIFE 1 0 is an interpreter for LIFE written in C The main design goals for Wild LIFE are functionality and robustness The interpreter implements most of the LIFE language and is robust enough to support serious program development To increase the system s general usefulness we have added a large number of useful tools and example programs As a general rule users of Wild LIFE are encouraged to use LIFE s unique features wherever possible They should not worry about low level efficiency issues but think only of using the expressive power of the language We are using Wild LIFE to develop a LIFE compiler We are making every effort to ensure that the compiler generates efficient code for well written programs Its design goals are to be competitive in speed with the best implementations of Prolog and to be usable for arbitrary large programs and data 2 Road map The purpose of this document is twofold it is intended as a tutorial to the LIFE language as well as a programmer s reference to the Wild LIFE system Table 1
142. lt in 26 abort built in predicate 56 acc_info declaration 111 accumulator 109 acc_info declaration 111 clause 110 composition gt 117 context 115 DCG 100 120 declaration 110 123 EDCG 110 equality 117 example program 109 initialization 112 119 interpret symbols 114 inversion inv 117 meta programming 114 pass info declaration 123 passed argument 123 pred info declaration 110 preprocessor 109 primitive init 119 insert 113 is 112 with 115 rule 121 scope 115 use of term expansion 125 Actor semantics 82 addition 41 aliasing 7 and built in function 43 appending two lists example program 27 apply built in function 88 Aquarius compiler 110 argv built in function 57 arithmetic calculation addition 41 bitwise and A 41 March 1994 Hassan Ait Kaci et al bitwise not V 41 bitwise or V 41 floating point division 41 integer division 41 lower integer part floor 41 multiplication 41 right shift lt lt 41 right shift gt gt 41 subtraction 41 upper integer part ceiling 41 comparison equal 43 greater than gt 42 greater than or equal gt 42 less than 42 less than or equal 2 42 not equal 242 43 invertibility 19 87 arity 97 array 84 asc built in function 46 ASCII code 46 48 49 assert built in predicate 74 asserta built in predicate 74 attribute 1
143. ment Example 8 27 This example gives a short program for copying files copy file F1 F2 open in F1 S1 oe Open file Fl Select it for input Open the target file Set output stream to stdout oe oe open out F2 82 open out stdout S3 oe write Copying from we n Bd mnm to we MEZ mmn und n3 set_output S2 Set the output to file F2 repeat get X Read a character If end of file F1 is reached then close both files oe X end of file close S1 close S2 oe write done output is reset to stdout and cut out the repeat loop else put X output the character fail Xx and fail to repeat loop Here is an example of its use copy file xxxooo junk Copying from xxxooo to junk done kKkK Yes 8 8 System related built ins 8 8 1 The Wild LIFE system This section summarizes the built ins that allow inspection and modification of Wild LIFE system related properties e The predicate list ing A1 Ao lists the definitions of the identifiers A1 A etc This predicate is non strict i e it does not evaluate its arguments This built in is quite useful to inspect a loaded program It knows about functions sorts including the sort hierarchy predicates and global variables For example try the query listing 23 e The predicate verbose toggles the Wild LIFE interpreter between two modes quiet and ve
144. ments if Research Report Draft March 1994 20 Hassan Ait Kaci et al that inference is unique For example the goal 0 B C unifies B and C The goal A A B does nothing since there are two possible solutions A 0 or B 1 This is a form of narrowing Example 6 3 Here is an example of residuation using the previously defined function fact First we impose the constraint A B i e A is the factorial of B using the fact function given earlier gt A fact B Yes Ay 0 B The expression fact B residuates yielding as a temporary result The tilde after means that B is a residuation variable i e a variable which if its sort is made more precise more information is known will cause the residuated function to be re evaluated 1 B real EXE YES A 8 B real The function fact still residuates because int lt real 2 B 5 Yes A 120 B 5 5 int so fact B 5 can be calculated Let us now go back to the previous query level by typing CR KKK No A B real 2 gt A 123 B 6 KKK No A 123 B real We have now strengthened the constraint to 6 123 and of course this constraint always fails Example 6 4 This example illustrates the execution order of a residuating functional evaluation in interaction with a calling predicate March 1994 Digital PRL Wild LIFE Handbook 21 gt p X write From p
145. missing period at the end of the string X 3 Thatis parse reports a syntactic error not a semantic one 8 7 4 Operator declarations In the same manner as Prolog Wild LIFE allows run time modification of input output syntax through operator declarations The predicate op P K N declares that the operator named N exists with precedence P and kind K This predicate is non strict i e it does not evaluate its arguments The precedence must be an integer from 1 to 1200 The kind must be one of xf yf x fy xfx xfy and yfx This predicate may be used to inspect or to create new operators See appendix B page 102 for a list of all predefined operators in the system The predefined operators are as compatible with ISO Standard Prolog as the language allows Example 8 25 This example illustrates user defined operators gt op 1000 fx if op 900 xfx then op 500 fx go op 600 x the op 700 xfx is op 1200 xf quickly VV V NN write if the weather is nice then go swimming quickly if the weather is nice then go swimming quickly k Yes Example 8 26 Return the list of all operators whose precedence is less than the precedence of ie which bind tighter than gt A bagof Z op X 3 gt op Y 3 gt Z Y lt X KK Yes A amp mod X Y Z Q Research Report Draft March 1994 54 Hassan Ait Kaci et al daa The op predicate recognizes keywords and therefore the t
146. mmary of functions and prototypes e Initialize Wild LIFE void WFInit int argc char argv e Submit a query int WFInput char query e Get a variable s value PsiTerm WFGetVar char name e Get the type of a 4 term char WFType PsiTerm psi March 1994 Digital PRL Wild LIFE Handbook 141 Get the value of a 4 term if it s a double double WFGetDouble PsiTerm psi int ok Get the value of a term if it s a string char WFGetString PsiTerm psi int ok Count the features of a 4 term int WFFeatureCount PsiTerm psi Get the value of a feature PsiTerm WFGetFeature PsiTerm psi char featureName e Get all the feature names as a NULL terminated array of strings char WFFeatures PsiTerm psi e Prove a goal and report an error to stderr on failure WFProve char goal 1 4 Memory management As LIFE is a non deterministic programming language it is best to view it as a coroutine running in tandem with the C program and which is queried by the C program Its execution state may be very different from the calling C program Wild LIFE uses its own memory management scheme with garbage collection At each call to WF Input the interpreter changes state and may completely re map its memory layout thus rendering obsolete any C variables pointing into the LIFE memory space Here is an example of dangerous programming PsiTerm a double n WFProve A 123 a WFGetVar A WFProve B fact
147. mplicit cut to remove all choice points created during the execution of P This function residuates until P is different from Example 8 4 This example illustrates call_once Research Report Draft March 1994 36 Hassan Ait Kaci et al gt p 1 2 OA 00 E gt A call_once p X KK Yes A true X 1 Sal 5 KkK No The second solution X 2 is not returned The function bagof X P returns a list containing as many elements as there are solutions to P This function is non strict i e it does not evaluate its arguments Each element of the list is the value of X for one solution of P Calls to bagof may be nested to any level There is no existential quantification such as in Prolog s bagof Example 8 5 This example illustrates bagof gt pla gt p b gt A bagof s X p X kkk Yes A s b s a X Es The function bestof X Q P returns the largest value of X for all solutions of P according to the total order Q This function is non strict i e it does not evaluate its arguments Calls to bagof may be nested to any level There is no existential quantification Example 8 6 This example illustrates bestof gt p 1 2 3 4 5 gt A bestof X gt p X Tcp VSS A 5 X 1 B bestof X lt p X ENE Yes A 5 B 4 X March 1994 Digital PRL Wild LIFE Handbook 37 e The predicate residuate X P attaches the predicate P to the term X If X is touched then
148. n The default is not to do term expansion expand load has no effect on interactive input The options A and W have the following effect e If the option A is t rue then expand the terms and assert them If A is true or false the first option is set to the value of A If A is a free variable then it is bound to the current value of the option Research Report Draft March 1994 60 Hassan Ait Kaci et al e If the option W is true then write the expanded rules and queries in a file with suffix exp This file can later be loaded to avoid re expanding all the rules If W is true or false the second option is set to the value of W If W is a free variable then it is bound to the current value of the option These options are recursive if filel is loaded with some options and loads file2 then file2 will be loaded with the same options If the second option is set the load file2 query in filel will be rewritten as 1oad exp file2 exp in filel exp load exp never does term expansion 9 Global variables persistent terms and destructive assignment This section covers three new concepts global variables persistent terms and destructive assignment These concepts are designed to provide clean and efficient replacements for most uses of assert and retract Global and persistent variable names are part of the name space that contains predicates functions and sorts The same symbol cannot denote both a predicate and a global variable
149. n order relation among themselves then the glb of r and s is given by the disjunctive sortir e In Wild LIFE if during execution a disjunctive sort is computed then it is not created or printed out as such Instead operationally it introduces a disjunction just as a predicate definition with several clauses introduces a disjunction March 1994 Digital PRL Wild LIFE Handbook 11 Example 4 3 Say we define a hierarchy containing the sorts two_wheels and four_wheels that represent classes of objects having respectively two and four wheels e bike two_wheels e bike vehicle truck four wheels truck vehicle car four wheels car vehicle From this hierarchy we can deduce the following values for the glb e glb two_wheels vehicle bike glb four_wheels vehicle car truck glb two_wheels four_wheels glb bike vehicle bike glb bike bike The disjunctive sort car truck is immediately enumerated 4 2 Attributes A term in its basic form is simply a sort A more complicated term is constructed by taking a sort and attaching attributes to it An attribute is a pair consisting of a label and an associated 1 term For example consider the term show title gt Bewitched genre gt sitcom where gt television mother_in_law gt Agnes Moorehead This term describes the set of records with at least the four fields title genre wher and mother in law This set
150. n the resolvent The new resolvent is the body Body followed by the remainder of the old resolvent Execution continues at step 1 4 If the unification in step 3 leads to failure then execution backtracks to the most recent choice point and continues forward from there LIFE uses succeed and fail as the predicates that are always satisfied and never satisfied respectively LIFE uses true and false as sorts that mean true and false March 1994 Digital PRL Wild LIFE Handbook 15 The above execution is similar to that of an imperative language such as C except that parameter passing is done by unification and execution may return to previous states by backtracking Example 5 1 Here is a two clause program which will print the items in a list one per line print list print list H T write H nl print list TI Print the first element Start a new line Print the rest of the list oe oe oe This translates in English to something like this e To print the empty list don t do anything e To print a list whose first element is H the rest being T write H and start a new line and print the list T And now we can try it out print list a b c a b C k Yes 5 3 Pruning the search tree with cut oy The built in predicate in Prolog or Wild LIFE pronounced cut allows the user to control the searching behavior of a program by cutting out alternative
151. name appears March 1994 Digital PRL Wild LIFE Handbook 39 Example 8 10 This example illustrates project gt A s a b A has two fields named 1 and 2 quw YES A s a b 1 B A 2 Select the field 2 KRK Yes A s a B B b 2 C A B Create the field b AUS ES A S lar By bu SSC B bp Coase e The function has_feature F X returns t rue if the term X has the feature F and false otherwise This function does not residuate and hence must be used with caution F may be passed as a string an integer or a sort The function features X M string returns a list containing all the features at tached to the root of term X which are visible in module M see Section 10 page 66 The order of the features is unspecified The module name M may be omitted in that case the module in which the call to features textually occurs is taken This function does not residuate and hence must be used with caution Example 8 11 This example illustrates features gt A features thing a b c next gt computer age gt 16 apple gt worms Ax Yes A 1 2 3 age apple next e The function root sort A returns the root sort of the term A The result is a copy of A without arguments This function does not residuate and hence must be used with caution Example 8 12 This example illustrates root sort Research Report Draft March 1994 40 Hassan Ait Kaci et al
152. nction and sort names Feature names are in an independent space a symbol may always be used as a feature name By current module we mean the module that determines the scope of the symbols at a particular time during execution A current module exists at all times during program execution both interactively and in a program A mechanism is provided which allows symbols to be accessed across modules For a symbol to be visible outside of its defining module it must be declared public in the module The syntax for an explicit reference to a given symbol defined in another module is module symbol Following standard terminology we call this a qualified reference For example the syntax built_ins write is legal if you are within module built ins or if write is declared public in module built ins which it is If the symbol contains non alphanumeric characters then the reference becomes module symbol It is not necessary to specify the module if the symbol you want to access is known in the current module The standard way of doing this is to open the module you are interested in with the built in open At that point all public symbols appearing in the module are visible in your current module March 1994 Digital PRL Wild LIFE Handbook 67 10 1 Standard modules Four standard modules are defined e Module built ins This defines all built in operations including predicates func tions and sorts e Module syntax Thi
153. nd s2 X s1 h gt slg and sas od tn proceeds like in case 3 with the only difference that the unifier has as root sort the g b of the sorts s1 and s2 5 Unifying two terms which have any sets of labels and two compatible root sorts s1 and s2 Some of the labels are common to both terms and others exist in only one term This proceeds as in case 4 the only difference is that the unifier term has the attributes obtained by unifying the terms at the common labels plus all the attributes that exist in only one term This allows one to program with hash tables in LIFE Research Report Draft March 1994 14 Hassan Ait Kaci et al 6 Unifying two terms which have any sets of labels and two incompatible root sorts r and s leads to failure as in case 2 5 Predicates Predicates are defined and executed in Wild LIFE in the same manner as they are in Prolog only terms replace Herbrand terms This is not a tutorial on Prolog so for information going further than the explanations given below please consult your local library 10 15 19 Except for differences in built ins Prolog programs can run unaltered in LIFE if they follow the syntactic convention that each predicate and functor symbol is used with one arity only See Section 15 for a complete list of differences between LIFE and Prolog 5 1 Defining predicates A predicate definition consists of one or several definite clauses Clauses are stored in the assertion
154. ndition means that if a label together with its value forms an attribute of the formal term then an attribute with the same label and a value has Research Report Draft March 1994 22 Hassan Ait Kaci et al to be present in the actual term and has to match t The third condition means that if two occurrences in the formal 4 term are aliased tagged with the same variable then this has to be true for the corresponding occurrences in the actual term A successful match is possible if the actual and the formal terms can be unified so that only formal variables are bound i e the actual term remains untouched To be precise this means that three conditions have to be met after the unification First a sort in the actual i term is intersected only with a supersort higher in the hierarchy Second no subterm in the actual term gets attributes with new labels Third an actual variable is not bound to another actual variable Example 6 6 A call to the following function diff X Y willfailif X and Y have been unified and succeed if X and Y are non unifiable Otherwise it will residuate Note that it residuates on all common subterms of X and Y This is necessary to guarantee that non unifiability is seen immediately gt diff X X gt fail gt diff X Y gt succeed diff X Y oo This residuates kkk Yes Xo a Y 47 1 X 1 Y 1 This also residuates kkk Yes X 1 Y 17 2
155. ng two terms consists in 1 computing the greatest lower bound glb of their root sorts 2 binding the root variables together 3 attaching to them all the attributes of the two parent 5 terms and 4 unifying recursively the terms in corresponding attributes If during this procedure a glb is found to be then the unification is said to fail Otherwise it is said to succeed Example 4 5 Here is a series of sample unifications that progressively illustrate the properties of term unification The last example is particularly interesting as it shows the unification of two cyclic terms Note that causes an immediate failure when executed The term X 1 is not the same as X 1 The latter is a function application See Section 6 4 The is different from the unification predicate The latter performs a calculation at run time For example in X foo bar gt X the term on the right hand side of is not bound to X until run time March 1994 Digital PRL Wild LIFE Handbook 13 Unifying results in v V int int car wheels 4 vehicle wheels N int car wheels gt N 4 int luck gt bad 13 roman gt XIII 13 roman gt XIII luck gt bad A B C i253 A 1 B 2 C 3 H T a b c d H a T b c d X s s X Y s s s Y X Y s X The unification of two terms corresponds to testing whether the intersection of the two sets of records described by the two terms is empty If it is nonempty th
156. often makes programs more readable more concise and more efficient We are using the Wild LIFE interpreter as a foundation to build a compiled system The emphasis in the compiler is twofold efficiency and scalability We are building a streamlined and powerful system that will make LIFE into a language that is every bit as fast and usable as the best existing implementations of Prolog 12 To help us in this endeavor please send us your comments and your Wild LIFE programs so we can use them as fuel for the compiler design March 1994 Digital PRL Wild LIFE Handbook 101 A LIFE versus Prolog It is our experience that once you have used LIFE you will not feel like ever using Prolog again The reason is simple LIFE provides clean and elegant solutions to a number of Prolog s most glaring deficiencies Here is a list l 2 9 10 Functions including correct arithmetic Object orientation C like records Expandable data structures arrays and hash tables Types and multiple inheritance Correct manipulation of cyclic structures Coroutining and constraints Global variables Clean destructive assignment Persistent data structures Semantically most of the above features are consequences of the two ways in which LIFE extends Prolog e Herbrand terms are replaced by 4P terms e Call by matching is added Prolog only has call by unification Most Prolog programs can be easily converted to run under LIFE
157. ogram that terminates no matter in what order the predicates in its predicate positions become known March 1994 Digital PRL Wild LIFE Handbook 91 Example 13 3 This example illustrates that the same result is obtained no matter when the predicate is known in a predicate position gt pla Define a single fact Q p X Q The predicate is known immediately kKkK Yes Q p X X a 1 gt KkK No gt Q Q p X The predicate is known with a delay k Yes Q p X KX a gt In general a function position may contain any term If the term is a function then the term is evaluated If the term is a predicate then the term is considered as a sort with only parent and only child If the term is a term then it is left unchanged The arguments of a term are considered to be function positions and hence are evaluated if they themselves are functions A predicate position may contain a predicate itself a function that eventually returns a predicate or a term that is eventually bound to a predicate The predicate position does not have to be bound immediately Example 13 4 This examples illustrates a function in a predicate position gt f A int gt write A oe Wait until A is an integer gt 23 Write 23 23 k Yes gt X X f Y Y 23 Write 23 23 Wes Mes X write Y Y 23 The order of predicate evaluation function evaluation and unification makes no difference in
158. old for the residuation variables It is possible to instantiate the set of residuation variables so that the rule fires It is possible to instantiate any one residuation variable so that the rule fails Multiple residuations can be attached to a single variable if there are multiple function calls with this variable in their arguments If the variable is unified then all the residuations are resumed The order in which the functions are resumed is deliberately left unspecified As with clauses the rules defining a function are looked up in the order they are entered The important difference is that functions are deterministic i e functional computations are determinate That is there is no backtracking once a rule has fired so the first rule to fire hides all those following it In the jargon of committed choice languages matching is a commit condition if the head of a rule is matched the execution is committed to take that rule Another way of seeing this is that functional evaluation does not allow argument guessing as would be non deterministically possible by narrowing i e using unification instead of matching when calling functions In order to unify the variables in the calling functional expression one has to use the built in function such that The built in arithmetic functions extend the above scheme in an important way they perform all deterministic local propagations That is they infer the values of one or more argu
159. olog MIT Press Cambridge MA 1990 16 Peter Van Roy useful extension to Prolog s Definite Clause Grammar notation ACM SIGPLAN Notices pages 132 134 November 1989 17 Peter Van Roy Can Logic Programming Execute as Fast as Imperative Programming PhD thesis Department of Computer Science University of California at Berkeley De cember 1990 18 Ehud Shapiro The family of concurrent logic programming languages ACM Computing Surveys 21 3 412 510 1989 19 Leon Sterling and Ehud Shapiro The Art of Prolog Series in Logic Programming MIT Press Cambridge MA 1986 March 1994 Digital PRL Wild LIFE Handbook Index built in function 41 gt see accumulator 121 function definition 17 built in function 42 built in predicate 66 lt lt built in function 41 built in predicate 66 Ginheritance declaration 8 7 built in function 42 gt gt built in function 41 gt built in function 42 built in function 41 built in predicate 16 built in function 41 built in function 41 bottom sort 9 A calculus 24 constrained sort 30 such that 27 35 T top sort 9 built in function 41 built in function 41 conjunction 34 project 38 projection 64 wild_life file 3 built in function 41 built in function 41 built in function 41 variable tag 11
160. on The toolkit module is loaded and opened with the command import xtools The toolkit is organized around three concepts namely boxes looks and constructors e boxes are used to compute the sizes and positions of objects on the screen All screen objects manipulated by the toolkit are subsorts of box e constructors are used to build and initialize screen objects All objects that have a behavior i e not simple graphical objects but real widgets inherit from one constructor type Ten of them are predefined e looks are used to describe the appearance of screen objects An object may be a subsort of several look types four such subsorts are predefined and will inherit the appearance of these looks These three concepts are defined as sorts and are organized in the following inheritance hierarchy multiple inheritance is possible from looks Boxes The next sections give details about boxes constructors looks and the predefined objects in heriting from these An example program is provided with the system in fileex tools 1f and should help the user to get started H 2 Boxes and their placement constraints All the objects manipulated by the toolkit are boxes A box is defined by the following type declaration box X Y width gt DX height gt DY March 1994 Digital PRL Wild LIFE Handbook 131 border gt B mother gt M X and Y are integers giving the coordinates of the top left corner of t
161. onbacktrackably 20 KKK No X 5 X is restored to backtrackable 5 9 It is important not to confuse lt and The former can be used on the standard data structures in a program The latter creates a special kind of data structure the persistent term which is useful for managing information that must not go away on backtracking For example the implementation of bagof uses persistent terms Attempting to use lt on persistent terms results in an error TheuseofA lt lt B where A isa local variable allows the creation of temporary persistent terms They are temporary because the binding to them is lost on backtracking before the instant in which the variable became persistent Example 9 3 This example illustrates nonbacktrackable destructive assignment gt persistent this gt p write this this is G when p is defined gt this lt lt q a b c Assign a value to this gt p Call p q a b c which prints the value of this kKkK Yes oe this q D E F Unify the persistent term q a b c Yes with the local term q D Q E Q F Q D a E b F c this q D E F Succeeds since q a b c q D E and F contain persistent terms Example 9 4 This example illustrates that subterms of a persistent term are persistent gt persistent that gt that lt lt thing int gt that thing 5 No Fails since int 5
162. ools written in LIFE This includes the X interface the graphical interface toolkit the accumulator preprocessor a debugger a profiler an extended user interface shell and a LIFE tokenizer and parser A set of libraries written in LIFE This provides collections of useful routines that are organized in modules to be imported when needed A set of example programs written in LIFE This includes SuperLint a lint like checker for C with user customizable checking rules a flower drawing program with an extensive X interface an incremental Gaussian equation solver a program to graphically display ib terms and a simulator of the PRL snack machine It also includes various smaller programs queens boxes PERT scheduler Hamming problem magic squares natural language parsing etc some of which use the X interface A test suite This is a set of more than three hundred programs containing more than 30000 lines of LIFE code These programs contain exhaustive tests of the capabilities of Wild LIFE along with code fragments from real programs The programs are accompanied with their inputs and correct outputs and two scripts check and check_all which can be used to test the correctness of the implementation The following email addresses are relevant to the LIFE language and the Wild LIFE system life users prl dec com Thisisamailing list of people using LIFE or interested in specific aspects of LIFE whether theory implementation or applica
163. ou use these predicates often you will find that Wild LIFE will spend quite a lot of its time collecting garbage 11 5 Summary of built ins e The predicate dynamic A A makes the routines A A etc dynamic i e they may be modified during execution This predicate should be used only as a declaration i e in a query and not in a definition This predicate is non strict i e it does not evaluate its argument Example 11 6 Attempting to prove a goal of a predicate without clause definitions results in an error unless the predicate has been declared dynamic in which case it simply fails gt foo Error foo is not a predicate or a function Abort dynamic foo VOU NES gt foo kKkK No e The predicate static A A makes the routines A1 A etc static i e they may not be modified during execution Any attempt to do so results in an error To modify them they must be made dynamic with a dynamic declaration This predicate should be used only as a declaration i e in a query and not in a definition This predicate is non strict i e it does not evaluate its argument The predicate assert C asserts the clause C of the form H B or H or the function rule C of the form H B at the end of the current definition H should be instantiated to a legal function or predicate name March 1994 Digital PRL Wild LIFE Handbook 75 12 The predicate asserta C asserts
164. panded and doesn t appear in the head of the clause is initialized this happens when with is used see below Initialization information may be given in the acc_info declaration in start and out_start features Example E A acc info einstein in start mc2 out start energy pred info t einstein S Is translated into S t in einstein gt mc2 out einstein gt energy as einstein doesn t appear in the head QQ If acc info is used several times to define the same accumulator only the last declaration is taken into account The system gives a warning e X is Acc unifies X with the current value of the accumulator Acc Example E5 with the previous declarations p p X is castor write X Y is pollux write Y p The obtained clause is p in castor gt A in pollux gt B out castor gt C out pollux gt D p in castor gt A in pollux gt B out castor gt E out pollux gt F G E write G H F write H p in_castor gt E in_pollux gt F out_castor gt C out_pollux gt D dct March 1994 Digital PRL Wild LIFE Handbook 113 It is also possible to write Acc is X same meaning as X is Acc Accl is Acc2 unify current value of Acc1 with current value of Acc2 Warning the expansion fails if none of the arguments of is is an accumulator supposed to be expanded e insert X Y Acc inserts X and Y in the chain implemen
165. pecified font on the window The font has to be loaded with xLoadFont The background pixels of the bounding box of the string are filled with the background color of the window Again X0 YO is the lower left coordinates of the string The default values and possible values are the same as for xDrawLine e Event xGetEvent Window eventmask gt EventMask Return an event in the window which matches the given mask The currently implemented events are mouse event keyboard event and expose event such that mouse button button B bool x X int y Y int keyboard event keycode gt K char gt C int expose event Eu Er Du For a list of the default values and possible values of EventMask see xCreateWindow If there is no event available the function residuates waits until one is Multiple calls to xGetEvent on the same window and or on multiple windows may be pending at the same time Research Report Draft March 1994 130 Hassan Ait Kaci et al H The graphical interface toolkit H 1 Introduction xtools isa simple toolkit to build interactive window based X applications in Wild LIFE It provides the user with the basic functionality of bigger toolkits in short the ability to use buttons text fields menus and sliders Composite objects containing these primitives can be created arbitrarily at run time The toolkit is built on top of the basic X interface described in the previous secti
166. predicates this means that all constraints are set before any generation is done and thus the satisfaction of the constraints is checked at every generation step This greatly decreases the complexity of the program Residuation can be used to mimic the behavior of delaying primitives such as when or wait declarations and freeze Here again residuation is used to increase efficiency or to avoid the non termination of programs Nevertheless residuation should be avoided when possible since it is a complex and ex pensive operation In many cases the programmer knows quite accurately how the variables in a rule are instantiated and can rewrite these so as to avoid as many useless residuations as possible For example V1I V2 2 L r V1 p V2 L should be rewritten Z V r V1 p V2 L V V1 V2 2 L March 1994 Digital PRL Wild LIFE Handbook 97 if you 14 3 know that the values of V1 V2 and L are computed by r and p Partial evaluation In programs where functions are used to denote constants it is sometimes possible to do a bit of partial evaluation to avoid computing these constants at runtime For example charHeightLogo gt 60 yO zm cellHeight gt 20 yLogo gt y0t tcharHeightLogo yTitle gt yLogo 2 cellHeight unit gt 10 Scale X X unit side gt scale 50 should be rewritten setConst X Y assert X gt Y charHeightLogo gt 60 yO gt 403
167. presents what is known of the length of gt listlen gt O gt listlen L gt s listlen L gt write listlen a b c A list of length 3 s s s 0 Fu YOS gt write listlen A list of length at least 2 s s Q LEX MES The result of a function can be a term that represents a predicate For this result to be executed as a predicate it must be in a predicate position i e in a place where a predicate is expected The result of a function can be a boolean i e a term whose root sort is true or false Such a function may be used in a predicate position The result true is executed as success and the result false is executed as failure A functional expression is a 1p term whose root sort name is a function name say f The attributes of the 4 term are its arguments A special case is the functional expression that constitutes the head of a function rule defining f its attributes are called the formal arguments Otherwise the functional expression represents a call to the function f then its attributes are called the actual arguments March 1994 Digital PRL Wild LIFE Handbook 19 6 2 Executing functions A functional expression F is evaluated in the following manner All arguments of a function are evaluated before the function is evaluated In what follows we assume that F contains no evaluable expressions in its subterms 1 Choose th
168. pty attribute list or nothing i e not but simply absence of an attribute list altogether const represents a constraint of the same form as is allowed in the body of a definite clause The declaration marked 8 is syntactic sugar for t attr const t u t lt v t w The declaration marked 10 is syntactic sugar for u attrl const v attr2 const w attr3 const u v lt w lt Cb CE 9 Please note the asymmetry of behavior of On one hand t u declares t as a subsort of u but on the other hand t u v w declares t as a supersort of u v and w An annoying consequence of this is thatt u is equivalenttou t whereas t u isequivalentto t u Similarly while t u means the same as t u itis not the case that t u v w meanst u v w but instead means u t v t w t Weare aware that these anomalies may not be palatable to all not even to some of us However one can systematically use the consistently behaving lt and avoid ever using Nevertheless still offers a conveniently simple shorthand to define such sorts such as tree leaf node left gt tree right gt tree which declares that a tree is a leaf or a node whose left is a tree and whose right is a tree Some may indeed argue that this looks like a more direct and natural translation than writing March 1994 Digital PRL
169. put 54 set output 54 setq 75 sin 42 sqrt 42 static 74 statistics 56 step 56 str2psi 46 strcon 46 strip 40 strlen 46 subsort 44 substr 46 succeed 34 system 57 tan 42 term expansion 59 trace 56 var 47 verbose 55 write 40 write canonical 49 writeq 49 xCloseConnection 126 xCreateWindow 126 xDrawArc 128 xDrawImageString 129 xDrawLine 128 xDrawOval 128 xDrawRectangle 128 xDrawString 129 xFillArc 128 xFillOval 128 xFillPolygon 128 xFillRectangle 128 xFreeColor 127 xGetEvent 129 xGetWindowGeometry 127 xHideWindow 127 xLoadFont 129 xOpenConnection 126 xor 43 xPostScriptWindow 127 Research Report Draft 151 xRefreshWindow 127 xRequestNamedColor 127 xSetWindowColor 127 xSetWindowGeometry 127 xShowWindow 127 built in sort hierarchy 10 built_in built in sort 9 button see graphical interface toolkit 134 C language 15 interface 140 memory management 141 C language 29 82 call once built in function 35 canonical form 49 ceiling built in function 41 children built in function 44 chr built in function 46 class 8 example program 82 clause 14 clause built in predicate 75 clause declaration 14 close built in predicate 54 CLP R language 87 colors 137 committed choice 19 compatibility with Prolog 97 compiler for LIFE 1 16 32 100 110 compatibility with Wild LIFE 1 0 1 25 71 75 self modif
170. r gt person age gt int gt man lt person gt A man KKK Yes A man age gt int The sort man is a subsort of person It inherits all attributes of person Sorts properties and inheritance in LIFE resemble classes class data and inheritance in a mainstream object oriented language like C See Section 12 6 page 82 for more details 7 1 Defining constrained sorts A sort that is given a sort declaration is called a declared sort There are two independent ways to declare a sort First it can be given a place in a hierarchy Second it can be given properties to check By default an uninterpreted identifier i e a symbol that does not occur in a predicate function or sort declaration behaves like a sort whose only parent is and whose only child is It is also known as an undeclared sort Predicates and quoted functions also behave in this way 7 1 1 Sort attributes A sort is given a w term property with a sort attribute declaration This is written as Head where Head is an arbitrary 7 term This attaches the property Head to the root sort of Head For example person age gt int ensures that all instances of person have the feature age whose value is an int Example 7 2 This example defines two sorts with attributes All vehicles have a make which is a string and a number of wheels which is an integer Research Report Draft March 1994 30 Hassan Ait Kaci et al vehicle make
171. r infor mation interchange between programs that do not necessarily have the same operator declarations The predicate n1 goes to the beginning of the next line i e it has the effect of printing a carriage return and line feed The predicate page width N changes the default page width to N By default the pretty printer invoked by pretty write uses a constant page width set to 80 characters This value is changed dynamically to the number of characters max 0 N The pretty printer is also used by the user interface to show the bindings of variables when a goal succeeds N must be a nonnegative integer or an unbound variable If N is an unbound variable it is bound to the current page width The predicate print depth N changes the default maximum print depth to N Only the first N levels of a term will be printed entirely The rest is printed as three dots N must be a nonnegative integer or an unbound variable If N is an unbound variable it is bound to the current print depth Since a term to be written may contain cycles the Wild LIFE printer explores it entirely to detect any cycles encountered It then prints the term generating new tag names to reference identical terms which appear several times and thus cycles in particular The tags generated are local to each call of the printer and are of the form _a where o is a capital letter or a sequence of same generated in alphabetical order thatis A B C
172. random with the current time e The function genint returns a new nonnegative integer each time it is called It is guaranteed that all calls to genint during a run of Wild LIFE will return different integers 8 3 2 Arithmetic comparison These functions narrow the sort of their arguments to real and the sort of their result to bool Their names are identical to Prolog s arithmetic comparisons They will residuate if their arguments are not actual numbers in the sort hierarchy They can be reversed in a few simple cases e The function A gt B returns t rue if A is greater than B e The function A gt B returns t rue if A is greater than or equal to B e The function A lt B returns t rue if A is less than B e The function A lt B returns t rue if A is less than or equal to B March 1994 Digital PRL Wild LIFE Handbook 43 e The function A B returns true if A is equal to B This is different from the unification predicate or amp the unification function The comparison is an arith metic function which does not unify its arguments always succeeds and returns true or false Nevertheless constraint lifting entails that if A 5 true then A 5 e The function A 1 B returns t rue if A is not equal to B This function unifies values in one case A 5 false where A will be unified with 5 8 3 8 Boolean arithmetic These functions perform calculations on boolean terms i e terms whose values ar
173. ration results in failure Normal and persistent terms each have their own destructive assignment operation Therefore there are two kinds of destructive assignment backtrackable and nonbacktrackable Both of these are useful in real programs See Section 12 7 page 83 for a non trivial example of the correct use of these two built ins 9 4 1 Backtrackable destructive assignment The predicate X Y overwrites X with Y X and Y are standard backtrackable 4 terms Backtracking past this statement will restore the original value of X For example gt X 5 X 6 X 7 succeed write X nl fail 6 7 5 K K No This predicate is very useful for building black boxes that have clean logical behavior when viewed from the outside but that need destructive assignment to be implemented efficiently 9 4 2 Nonbacktrackable destructive assignment The predicate X Y overwrites X with a persistent copy of Y Modifications to X after it has been made persistent are not backtrackable If you backtrack to a point before X is made persistent then X is restored to its original backtrackable value For example gt X 5 xk xk Yes X 5 1 gt X lt lt 10 Make X persistent with value 10 kKkK Yes March 1994 Digital PRL Wild LIFE Handbook 63 X 10 2 X lt lt 20 oe X gets value 20 nonbacktrackably KKK Yos X 20 cie 3 Type CR to go back KEK No X 20 2 gt X is n
174. rbose The interpreter starts up in quiet mode Verbose mode gives execution time statistics about each query and shows the garbage collections when they occur The statistics given in verbose mode are the following Research Report Draft March 1994 56 Hassan Ait Kaci et al CPU time of the query in seconds Number of internal goals executed by the query Size of backtrackable stack in bytes Size of nonbacktrackable stack in bytes goals Number of internal goals on goal stack choice points Number of entries on choice point stack trail entries Number of entries on trail stack Example 8 28 This example shows how to declare a function with variable arity i e the number of arguments is determined by each call gt X sum gt sum_all features X X gt sum all F FL X gt X F sum all FL X sum all O EXE Nes gt verbose A sum 1 2 3 4 5 Verbose mode is turned on Yes 0 000s cpu 80 goals 7916 stack 196624 heap Stack depths 0 goals 0 choice points 1 trail entry A 15 The predicate statistics prints information about the current memory usage of the system The predicate t race X is used to enter and exit trace mode In trace mode all internal goals are printed to stdout If X is false then trace mode is disabled This is the default If Xis true then trace mode is enabled If X does not exist then trace mode is toggled The predicate step X is used to
175. rder If sufficient information is given to solve the equations the result will always be correct Since each function invocation is calculated only once the result is calculated in linear time regardless of the amount of sharing in the dependency graph It is in general difficult to predict when the different calculations will be done but this is irrelevant because it is not necessary 12 3 Cryptarithmetic SEND MORE MONEY This example shows an efficient way of solving the standard benchmark test SEND MORE MONEY where each letter codes one digit and no two letters code the same digit The algorithm is based on test and generate That is a series of function calls is done which all suspend Then the variables are instantiated to all possible digits The sus pended functions act as passive constraints to prune the search The computation terminates successfully only when an assignment of digits to variables is found that is consistent with all the passive constraints solve s Solutions with M 0 are uninteresting M 1 The arithmetic constraints C3 S 4 4 M 0 10 M C2 E O N 10 C3 Cl N R E 10 C2 D E Y 10 Cl The all distinc onstraints t con diff _list S E N D M O R Y Generating binary digits Cl carry C2 carry C3 carry Generating decimal digits March 1994 Digital PRL Wild LIFE Handbook 79 S decimal E decimal N decimal D decimal
176. re the first argument is the input and the second the output The arrows represent the unified arguments Research Report Draft March 1994 116 Hassan Ait Kaci et al head accl bodyl accl acc2 The clause is thus expanded to head in_accl gt A out_accl gt B bodyl in_accl1 gt A out_accl gt C in_acc2 gt out body2 in_accl gt C out_accl gt B in_acc2 gt out body3 in_acc2 gt D out acc2 Q _acc2 gt D acc2 2 5Q ct ct c1 When an accumulator appears in the right hand side of a with and in the parent context the expansion of the accumulator inside and outside the scope of the with are totally independent arguments appearing inside the scope of the with won t be linked with arguments appearing outside Example E10 p Y q with castor 1s translated into p in_castor gt A in pollux gt B out castor gt C out pollux gt D r in castor gt A out castor gt C q in castor gt E in pollux gt B out castor gt F out pollux gt D The arguments implementing the accumulator castor in q are not linked with the others pollux is regularly expanded E2 2 Operations The notion of context gives the possibility to perform operations on accumulators In a context an accumulator is represented by a pair of arguments In Out In the example above the castor accumulator is represen
177. rectangle with identical length and width The latter can be refined into the former March 1994 Digital PRL Wild LIFE Handbook 31 Example 7 4 This example defines a subtype of list int_list which defines lists that contain only integers This property is guaranteed to be true for an int list This definition does not interfere in any way with existing code using lists An int list will work with existing list based routines int list list int cons cons int nil lt lt Xl int cons int int list cons int list mna lit lAs ts int int Here is an example query gt X 1 2 3 X is a standard list BEAN ES X 1 2 3 1 gt X int_list X is an int_list XER Yes X int cons 1 int cons 2 int cons 3 int nil 2 Y length X Calculate the length of X KKK Yes X int_cons 1 int_cons 2 int_cons 3 int_ni1 Y 3 7 2 Executing constrained sorts The Wild LIFE system guarantees that all instances of a sort are consistent with all decla rations of that sort For the inheritance hierarchy this is guaranteed by term unification see Section 4 1 3 page 10 Consistency with properties is guaranteed by a mechanism called sort unfolding Sort unfolding makes a copy of the declaration and unifies it with the term Each declaration is checked at most once for a given sort instance This performs a kind of memoization i e the solution of an intermediate problem
178. red A curried functional expression A may only be used in functional applications of the form A j gt X 1 7 X Example 6 8 This example shows the difference between currying and residuation We define a function in one argument which is a 4 term with three attributes We call it with a term with only two attributes Hence the functional expression residuates and returns as its value If its argument gets more instantiated by adding the missing attribute the function fires This is possible only once gt g eggs gt X bacon gt Y toast gt Z gt X Y Z gt A g B eggs gt a bacon gt b write A WS VES 1 gt B toast gt c write A Fire the function g a b c Example 6 9 We define the function h with labels 1 2 and 3 Since these are consecutive numeric labels they do not have to be explicit If the function is curried in the first two arguments then we need to give the label 3 explicitly If the function is curried in the third argument then we can leave the labels 1 and 2 implicit since they are consecutively numbered from 1 Research Report Draft March 1994 24 Hassan Ait Kaci et al gt h A B C gt A B C gt Xl h a b X2 h 3 gt f K K Yes X1 h a b X2 h 3 gt f 1 Y1 X1 3 gt c Y2 X2 d e write Y1 write Y2 a b c d e f 9 Currying in Wild LIFE is not defined in the usual way because the list of required arguments is
179. riginal data structure 4 term and its use in predicates functions and sort type definitions Along the way many useful examples are provided and some common pitfalls are discussed and illustrated R sum Ce manuel fournit un cours d initiation au langage de programmation LIFE ainsi qu une description d taill e des pr dicats et fonctions pr d finis dans l interpr te Wild LIFE 1 0 C est la premi re fois que nous tentons d crire une introduction pratique la programmation en LIFE Bien que nous fassions l effort de n utiliser que des notions l mentaires ou pr definies il est pr f rable que le lecteur ait d j une connaissance de base de Prolog Le cours expose graduellement et de facon synth tique les principales composantes de LIFE sa structure de donn es originale le p terme et son emploi dans les clauses les fonctions et les d finitions de sortes types Beaucoup d exemples utiles sont donn s tout au long du manuel et quelques pi ges courants sont illustr s et discut s Keywords Constraint programming logic programming functional programming object oriented pro gramming rapid prototyping inheritance Acknowledgements The Wild LIFE project has been very much a team effort The low level X Window interface was implemented by Jean Claude Herv The graphical interface toolkit and accumulator preprocessor were implemented by Bruno Dumant We thank the other past and present members and visito
180. rm but between any subterms we may attach tags i e variables to any subterms of a term In particular this allows us to describe cyclic structures Example 4 1 Here are a few sample 4 terms e 42 a specific integer int the sort that denotes all integers 5 66 a specific floating point number 2 10776e 8 a specific floating point number in exponential notation real the sort that denotes all floating point numbers a small piece of rope a specific string string the sort that denotes all strings abc def l a sort strange characters asortwhosename contains strange characters note the single quotes e date friday XIII a w term with implicit numeric labels e date 1 gt friday 2 gt XIII the same term with explicit numeric labels e date 2 gt XIII 1 gt friday the same term yet again showing that the order of explicit labels is irrelevant e freddy nails gt long face gt ugly films gt 5 a v term with keyword labels e rectangle width gt S int length gt S a term with two attributes that are aliased together as indicated by the tag S e X person home gt address occupants gt X a v term with a cyclic reference as indicated by the tag X Tf you substitute Prolog terms by LIFE s terms the resulting language is called Login 4 Research Report Draft March 1994 8 Hassan Ait Kaci et al A 4 term describes a set o
181. rs of the Paradise project at PRL and its follow on the Proteus project for their suffering along with the final debugging of the design and delivery of Wild LIFE We appreciate their active and continuing participation giving many examples bug reports and constructive criticisms For the final haul on version 1 0 we especially thank Arnaud Venet Contents 1 Introduction 2 Roadmap 3 Running Wild LIFE 31 Gota SAO 4 4 ook eee dee tert n yr e metet se wah eels od 3 2 DULL SVO uestem Ser trux Ru eR ERE Hec ose iiec 3 3 Incremental query extension 0 0 3 4 Loading files 2 x usos fe alc oA e de e al etae 3 5 Interrupting execution e e e 4 The basic data structure v terms Zap ROME bl a a eet oco eoe 41 1 Defining sort inheritance ee 4 2 B llbinisorts 4 eb E Erbe deme deu ue 4 1 8 Greatest lower bound gl llle 4 25 AHIBULGS stude um tog ente vL t e de TROC dee 435 WVariables and tags du d acces ox eeu ret ee at een de SEIDIeatioNT vows mox E utis aru ee words E 4 4 1 A step by step comparison with Prolog unification 5 Predicates 51 Defining predicates aud ve ee Ge ae Bate ee cx ee 5 2 Executing predicates llle 5 3 Pruning the search tree with cut 0 5 8 1 The scope ofcut 5 8 2 Disjunctive terms and cut llle 5 8 8 Negation as failure l
182. s i e ending with a period instead of a question mark Research Report Draft March 1994 126 Hassan Ait Kaci et al G The X interface Wild LIFE provides an X interface that allows programming X applications at the LIFE level To speed up Wild LIFE s start up time the X library is not loaded by default Any program using X must first import load and open the X interface module with the command import x For examples of how these routines are used look at the sample programs provided with the Wild LIFE release A before a variable name means the field is an input and a means it is an output Arguments mentioned as default may be left out in that case the default values are used Certain arguments may not be changed by the LIFE programmer they may only be created by X routines and passed into X routines This includes the Display Window and Font arguments A few arguments must be strings these are indicated by the notation string For additional functionality that makes it very easy to create interactive window based applications with buttons menus and so on the graphical interface toolkit should be imported See appendix H for more information G 1 Event mask values The named event mask types are NoEventMask xKeyPressMask xKeyReleaseMask uttonPressMask xButtonReleaseMask xEnterWindowMask LeaveWindowMask xPointerMotionMask xPointerMotionHintMask ButtonlMotionMask xButton2MotionMas
183. s defines the minimal symbols required for parsing LIFE files This comprises operator declarations the operator symbols themselves and all non alphabetic symbols related to parsing such as and so forth e Module x This contains all of the built ins related to the X interface A program using the X interface must first load and open it with the command import x For an example of its use see the X toolkit presented in appendix H e Module user This is the current module at system startup It is the default module for interactive input to the system Currently the modules syntax and built ins are always open so their symbols may be accessed without specifying a module name There is no means to override this 10 2 Using features To make things easier for the LIFE programmer features are public by default If you want to have private features then the predicate private feature can be used in the same way as private It is possible but unwise to define a feature as being private while the corresponding symbol is public The function features will only return those features which are visible from within the module the call appears in Example 10 1 module secret public prison private feature entrance prison entrance tunnel V VV M V module user gt open secret P prison door guarded xk xk Yes P prison door gt guarded entrance gt tunnel 1 d
184. s from the search tree Executing a cut is like executing succeed but with a side effect it removes all the alternatives which occurred from the moment the rule was chosen to the moment the cut is reached This means that the next rules in the predicate s definition will not be tried and any alternatives that may have arisen during the proof of the current rule will not be explored either The Wild LIFE 1 0 interpreter does no clause indexing This means that each clause of a deterministic predicate should contain a cut The cut must be placed at the earliest point in the clause body where you are sure that if execution reaches that point that the correct clause has been selected No bindings to variables visible outside of the predicate should be done before the cut This condition ensures that the cut does not change the predicate s semantics i e it is a green cut 15 The print list example given above contains a correct use of cut The cut predicate is useful because it allows one to reduce the number of alternatives especially if you know for certain that all alternatives would fail For the interaction of cut and functional evaluation including residuation and coroutining see Section 6 5 8 1 The scope of cut The choice point associated to a cut is linked to the environment that existed when the cut was first encountered by the interpreter If a goal passed as an argument contains a cut that Research Report Draft March 1994 16 Hass
185. s of a particular kind These functions never residuate Hence they are order dependent and should be used with caution They can be made order independent by wrapping them in another function definition e The function is function X returns t rue if X is a function e The function is_predicate X returns t rue if X is a predicate e The function is sort X returns t rue if X is a declared sort A declared sort is one that has occurred in a or declaration e The function var X returns t rue if X is with no arguments e The function nonvar X returns t rue if X is not Q or it has arguments or both e The function is persistent X returns t rue if X is a persistent term See Sec tion 9 8 7 Input output In Wild LIFE as in Prolog input and output operations are extra logical in that they have side effects Namely Wild LIFE does not upon backtracking retrieve information that has been sent to an output port or put back characters read from an input stream Therefore good style dictates that input output be avoided in the main body of a program Research Report Draft March 1994 48 Hassan Ait Kaci et al Unless explicitly set otherwise by the user all reading and writing is done from and to streams bound to the standard Unix I O file descriptors stdin and stdout We first describe the built ins for reading and writing on the currently selected I O stream Then we describe how to modify the current stream 8 7
186. s used to declare function rules The operator precedence for arithmetic comparisons is 600 instead of 700 since comparisons occur in expressions No operator declarations are given for is No rem and the standard order comparisons lt lt gt and gt Disjunctions are the same as in Prolog In addition to these there is also a kind of disjunction the type disjunction which returns a value Type disjunctions may be used inside terms They allow compacter code They are written with braces and instead of parentheses For example the following two queries are equivalent gt ARTE AR ele AS ASIA ASIST gt DE 132537 45 5h 12 Negation as failure does not work exactly as you might expect if functions are involved See Section 5 3 3 page 16 e DCG expansion in Wild LIFE adds arguments with labels in dcg and out_dcg See appendix F page 109 16 Conclusion the experience of Wild LIFE We hope that this short handbook will incite readers to program in LIFE The interpreter we describe Wild LIFE version 1 0 has been stable for almost a year in its present state It has been used and tested extensively and we are confident of its robustness and usefulness It has most of the functionality of the complete language Getting to grips with LIFE is not hard if you are familiar with Prolog For Prolog program mers the extra power of terms sorts and functions is a welcome addition that
187. seful for debugging Wild LIFE programs using the 1isting predicate If X does not exist then the module display mode is toggled Example 10 6 This example illustrates di splay modules gt display modules true A hello KK Yes A user hello 11 Rule base management The predicates in this section have been added for compatibility with Prolog They may not be supported in the compiler They should be used only when it is necessary to create or modify a program during execution They should not be used for storing data i e p terms They should not be used if the program requires a global name to store a term and or if it is required that a term continue to exist on backtracking Section 9 provides better solutions for both of these cases It is strongly discouraged to modify a routine during that routine s execution The current release of Wild LIFE provides for immediate update semantics in certain cases as given below It does not implement the defensible semantics of 11 11 1 Adding rules The built in predicates assert C and asserta C add the clause C to the program The argument C may be of two forms Head Body or simply Head the latter be ing equivalent to Head succeed The Head must be a dynamic predicate With assert the clause C will be added as the last rule to be tried for that predicate With asserta itis added as the first rule Example 11 1 This example illustrates assert gt asser
188. ses are identical as long as the bar predicate does not contain things like destructive assignments on its out dcg feature When code is inserted for instance a cut we have to make sure that this folding does not bind variables occurring before the insertion Consider the following clause foo gt t 11192 This first translation of it with folding foo in dcg gt 1 A out_dcg gt A does not have the same behavior as this one without folding foo in dcg gt A out dcg gt B e a A 1 B The first translation is not correct w r t the usual meaning of cut The translator we propose here deals with this in a very simple way no folding is performed after a cut or a code insertion FoldOk is the variable used in the translator telling whether folding is authorized or not Code Insertion There are two ways of translating a rule like foo pred Either as foo in dcg gt A out dcg gt B pred A B Or as foo in dcg gt A out dcg gt A pred In most cases those two translations will have exactly the same behavior but if some side effect is expected from pred they may differ This is the case if pred is a cut for instance The translation used here is the second one namely foo gt pred is equivalent to foo pred The other alternative may be obtained by writing foo gt pred March 1994 Digital PRL Wild LIFE H
189. side S q in castor gt QG out castor gt A in pollux gt A out pollux gt 8 The same clause could have been specified in the following way S q with castor N X pollux X N Research Report Draft March 1994 118 Hassan Ait Kaci et al Graphically castor pollux hh Y y q castor pollux hh u 11 Nu VY The constraints imposed by the right argument are represented by solid arrows the other links by dashed arrows e s q with inv castor gt pollux inv inverts input and output arguments In this example you may notice that both inputs are linked together S q in castor gt A in pollux gt A out castor gt out_pollux gt Q e s q with castor pollux Equality of accumulators means unification of both input and output S q in castor gt A in pollux gt A out castor gt B out pollux gt B ep q with glob castor castor gt pollux glob castor is a reference to the castor accumulator appearing in the parent context p in castor gt A in pollux gt B out castor gt C out pollux gt B q in castor gt A in pollux gt D out castor gt D out pollux gt C Graphically March 1994 Digital PRL Wild LIFE Handbook 119 p castor pollux IM castor pollux hh hh Y Y
190. solution cuts out all alternatives and fails If there are no solutions to G then the next rule is used for not and this always succeeds This does not quite do what you expect because all the parameters of X have been evaluated before they were passed In other words functions disjunctions and sorts that needed evaluating have been dealt with so A write a b c for example will print abc before failing Example 5 4 This example shows the use of a variable name in a query to replace a goal This form of negation is often unsound Functions in LIFE provide sound negation for equalities March 1994 Digital PRL Wild LIFE Handbook 17 X write Here I am KKK Yes X write Here I am 1 X Here I am kkk Yes X write Here I am For more information on using variables as predicates see Section 13 3 page 90 6 Functions In LIFE a function is a routine that is called by matching and that returns a result Functional computations are determinate i e a function call only fires once and is never backtracked to A function may be called before the values of its arguments are known In that case the function will suspend Technically a function that suspends is said to residuate and the suspension is called a residual equation or residuation The function will execute as soon as its arguments are known A function may also be curried i e called with missing arguments Residuation an
191. t 1 Run the queens program WFProve import 042queens 042 WFProve queens Loop over each solution do sleep 1 printf retryingin ans WF Input printf ans dMn ans while ans March 1994 Digital PRL Wild LIFE Handbook 145 References 1 10 11 12 Hassan Ait Kaci Robert Boyer Patrick Lincoln and Roger Nasr Efficient implementa tion of lattice operations ACM Transactions on Programming Languages and Systems 11 1 115 146 January 1989 Hassan Ait Kaci and Jacques Garrigue Label selective A calculus PRL Research Re port 31 Digital Equipment Corporation Paris Research Laboratory Rueil Malmaison France 1993 Hassan Ait Kaci and Patrick Lincoln LIFE A natural language for natural language TA Informations 30 1 2 37 67 1989 Association pour le Traitement Automatique des Langues Paris France Hassan Ait Kaci and Roger Nasr LOGIN A logic programming language with built in inheritance Journal of Logic Programming 3 185 215 1986 Hassan Ait Kaci and Roger Nasr Integrating logic and functional programming Lisp and Symbolic Computation 2 51 89 1989 Hassan Ait Kaci and Andreas Podelski Functions as passive constraints in LIFE PRL Research Report 13 Digital Equipment Corporation Paris Research Laboratory Rueil Malmaison France 1991 Hassan Ait Kaci and Andreas Podelski Towards a meaning of LIFE P
192. t The following execution fragment shows how to couple the function map with residuation BA calculus handling currying with named arguments and consumption by position is presented in 2 March 1994 Digital PRL Wild LIFE Handbook 25 gt fact 0 gt 1 gt fact N gt N fact N 1 gt R map F 4 5 6 7 Yas F dais R 1 F fact kKkK Yes F fact R 24 120 720 5040 Example 6 12 This example defines a function with two rules where each rule has an argument with a different label The function will curry if arguments are missing relative to the rule being matched against Taking advantage of this behavior is bad programming style in Wild LIFE and will probably be forbidden in the compiler gt foola gt int gt 1 gt foo b gt int gt 2 gt X fo0 b gt 0 Jo Yes X foo b gt 0 1 Y X a gt string AUR eS X foo b gt 0 Y 2 Example 6 13 This example shows how residuation currying and functional variables can be combined together a constraint is generated which binds the variable R to the result of applying F to A where at that point both F and A are unknown Later the argument A is chosen by the predicate pick_arg and the function F by the predicate pick_function Note that 2 gt 4 is a curried function which multiplies its first argument by 4 Define the following predicates in addition to act seen before pick arg 5 3 7 pick func
193. t in predicate 49 qualified reference 66 query 3 execution 14 extension 4 level 4 89 self reproducing 52 quoting functions 26 global variables 65 persistent variables 65 random built in function 42 random numbers 42 rational tree 99 read built in predicate 48 read token built in predicate 48 real built in sort 9 real time built in function 58 record 7 recursive sort 31 redundancy 34 residuate built in predicate 37 residuation 17 96 Digital PRL Wild LIFE Handbook difference with currying 23 example 76 passive constraint 78 use in debugging 37 variable 19 residuation variable 19 resolution 14 resolvent 14 retract built in predicate 75 root sort 8 root sort built in function 39 roundoff error 41 routine variable arity 56 rule 17 rule declaration 17 rule base management 71 scope see accumulator 115 self modifying code 71 self reproducing query 52 SEND MORE MONEY example pro gram 78 set input built in predicate 54 set output built in predicate 54 setq built in predicate 75 sh Unix shell 57 sharing in term 12 sieve of Eratosthenes example program 84 Simplex algorithm 88 sin built in function 42 sine 42 single stepping 6 56 SLD resolution 14 slider see graphical interface toolkit 134 Smalltalk language 82 sort 7 8 20 bottom 9 built in bottom 9 top 9 bool 9 built in 9 Research R
194. t q write rulel assert q write rule2 Research Report Draft March 1994 72 Hassan Ait Kaci et al kk Yes gt q rulel KK K Yes 1 gt rule2 kc Yes When the last rule for a goal is being used Wild LIFE does not create a choice point for that goal so if you add a new clause it will not take effect this is shown in the following example gt p 1 KKK Yes gt p A write A assert p 2 fail 1 KKK No The alternative p 2 was not considered because when the rule p 1 was used there was no alternative clause at that time 11 2 Deleting rules The predicate ret ract C removes the first clause which unifies with C If there are more than one then backtracking will successively remove the others Example 11 2 Itis possible to write the function genint which returns a new distinct symbol each time it is called in the following manner genint_counter 0 genint N retract genint_counter N M N 1 assert genint_counter M This is not the best way to write genint A better way is to use a persistent term persistent genint_counter genint_counter lt lt 0 genint gt copy_term genint_counter genint_counter lt lt genint_countertl Example 11 3 Wild LIFE supports immediate update semantics If you retract a clause which is currently being used then any currently active clause one which is in the process of being executed or one which is reachable by backtrackin
195. tate is a persistent term LedOn The color ID used when State is true The color values are found in main colors highlight colors and shade colors depend ing on the part of the led see Colors below Default is d led on LedOff The color ID used when State is false Default is d led off H 4 2 Inheritance of looks Looks are inherited through subtyping For instance on off button is a subsort of text box led and frame Note that the color id feature appears in frame and field Therefore they should be compatible H 4 3 Colors and fonts Colors and fonts are stored in tables There are three tables for colors main colors highlight colors shade colors and one table for fonts Colors and fonts are accessed through identifiers that may be any atom All objects have default colors stored in xtools constants To change the color of an object you have to e Store a color in the appropriate table with the ID you have chosen using the predicate def color Table Id Color for a font def font Id Font e Set the appropriate color ID of the object to Id Example H 1 To have a class of text boxes with red text March 1994 Digital PRL Wild LIFE Handbook 137 def color main colors my id red my txt text box my txt text color id gt my id As the same color id feature appears in field and frame if a color is defined for the IDIinmain colors thenthe corresponding colors for the same
196. te on it It can be modified only through explicit calls to nonbacktrackable assignment see Section 9 4 2 This can be viewed as having a global database a set of graphs with named entry points on certain nodes All subterms of a persistent term are also persistent Information may be shared between persistent terms Persistent terms are stored on the heap just like clauses see Section 8 8 1 Persistent terms cannot be unified together They can be modified only through destructive assignment All interaction between local terms and persistent terms is through matching An error is reported if the match fails Any attempt at unifying two persistent terms yields an error A persistent term may be stored in a standard variable Modifications of the term are unaffected by backtracking Access to the term through the standard variable is affected by backtracking if one backtracks before the point in which the standard variable obtains access to the persistent term then the standard variable gets its original value back and the persistent term becomes inaccessible Its space is recovered by garbage collection 9 3 Persistent variables A persistent term may be stored in a global variable The variable is then called a persistent variable In this case the value never becomes inaccessible Parts of persistent terms may be shared between variables Persistent variables must be declared The 1isting predicate knows about global variables but it
197. ted by the pair A C in the head context and the pair E F in the context defined by the with operator We define three operations on these pairs of arguments composition inversion equality March 1994 Digital PRL Wild LIFE Handbook 117 e Composition gt A B C D retums A D B and C are unified e Inversion inv inv A B returns B A e Equality A B C D unifies A and C and B and D Moreover direct access to the pairs of arguments is given which allows the accumulators to be initialized in a convenient way The right hand side of the with operator contains a conjunction of constraints to be applied to the new context either simple constraints meaning expand this accumulator locally or more complex like compose these two accumulators or make these accumulators equal What follows is a set of example clauses and their translations es q with castor 1 2 3 When arguments are given to accumulators in a scope of a with the first one is unified with the input of the accumulator the second with the output The above clause is translated into S q in castor gt in pollux gt 8 out castor gt 1 2 3 out pollux gt This may be represented graphically by S e s q with castor gt pollux gt is the composition operator It links the output of its left hand side with the input of its right hand
198. the quiet mod This Virtual memory usage is close to 2 N because of the half space garbage March 1994 Digital PRL Wild LIFE Handbook collection algorithm used arguments All command line arguments are available to the LIFE program The function argv returns a list of strings where each string is one command line argument 107 The default value of N is 2000000 E For example if the system is started with wild life q foo then argv returns the list wild life FILES Lifel Lifel Lifel Lifel Lifel Lifel Lifel EXAMPLES H o wild life 0 0 0 0 0 0 0 Doc Examples Lib Tools CLife Tests Source The directory Lifel 0 q foo a documentation example programs libraries programming tools wild_life as C library test suite source code Wild_Life Interpreter Version 1 0 Copyright C No customizing file loaded import solve File udir rmeyer LIFE PUBLIC Il KK K Yes gt solve Examples contains a set of example programs Each of these programs is in its own module and can be loaded directly into the interpreter with the import command he following example shows how to run a program that solves the END MORE MONEY puzzle 1991 93 DEC Paris Research Laboratory Examples solve lf loaded SEND 9567 MORE 1085 MONEY 10652 No
199. the sort This allows the fact of being prime to be remembered by the number itself This is a good illustration of the expressive power of the sort hierarchy prime I int length factors 1 1 factors N int gt cond N O O factorize N 2 factorize N P gt cond P P gt N N cond R N P floor R P factorize R P factorize N P 1 The first rule reads as a prime is an integer I such as the number of dividers of I is 1 The function factors yields a list containing the factorization of its argument Let s have a look at what this program does Research Report Draft March 1994 76 Hassan Ait Kaci et al gt write factors 6450 nl write factors 127 25 84 Atop A 43 127 KK K Yes gt 6 prime kkk No gt 43 prime EXE Nes gt P prime JW YES P prime 1 P 29 KKK Yes P 29 prime 2 repeat write prime amp natural fail O prime 1 prime 2 prime 3 prime 5 prime 7 prime 11 prime 13 prime 17 prime 19 prime 23 prime 29 prime 3l prime 37 prime 41 prime 43 prime 47 prime 53 prime A number of sort prime will not be checked twice As P prime has no value the function factors residuates which causes length to residuate too then the instant an integer with a value is unified with P these two expressions are released and succeed or fail By coupling prime and natural itis possible to generate all prime numbers 12 2 PERT schedulin
200. ting Acc This primitive is provided as an escape to standard LIFE code It should not be needed in most cases Example E6 with the previous declarations r 2 r insert a b casto r r The obtained clause is r in castor gt A out castor gt B r in castor gt A out castor gt C a C b D r in_castor gt D out_castor gt B e cond and disjunctions Expansion is performed inside cond and disjunctions e Code insertion The preprocessor may be told not to expand a piece of code by inserting it between brackets Example E7 with the previous declarations p m Y 7 fps The obtained clause is p in castor gt A in pollux gt B out castor gt C out pollux gt D q in castor gt A in pollux gt B out castor gt C out pollux gt D p Research Report Draft March 1994 114 Hassan Ait Kaci et al Use of cut Cuts may be used anywhere and are never expanded is in fact syntactic sugar for Ter E Meta programming Variables may be used as symbols in the body of the rules Example E8 with the declarations above p X X Is translated into p X in_castor gt B in_pollux gt C out_castor gt D out_pollux gt E interpret_symbols X castor gt B pollux gt C castor gt D pollux gt E a cname default C gram gt false The features of interpret
201. tion substr 46 length strlen 46 parsing parse 52 comparison equal 22 47 greater than gt 47 greater than or equal gt 47 less than 47 less than or equal lt 47 not equal 47 string built in sort 9 strip built in function 40 strlen built in function 46 subsort built in predicate 44 substr built in function 46 substring extraction 46 subtraction 41 subtyping of lists example program 30 succeed built in predicate 34 such that 27 35 resemblance to constrained sort defini tion 30 March 1994 Hassan Ait Kaci et al sum 41 suspension 17 symbol 66 synchronization 17 syntax error 6 system built in function 57 tag 7 11 tan built in function 42 tangent 42 term see 1 term 7 term expansion use in preprocessor 125 term size calculation example program 83 term expansion built in predicate 59 test suite 105 test and generate 17 78 tilde 20 time measurement 58 tokenizer 105 top sort O 9 top level interface 4 trace built in predicate 56 tracing execution 6 trichotomy 45 true built in sort 9 type 8 type disjunction 34 undeclared sort 29 undocumented built ins 1 unification 12 built in function amp 38 built in predicate 38 choosing between matching and unifi cation 27 unification function 38 unification predicate 38 uninterpreted identifier 29 9
202. tion definitions aaa A RO Bee RS 73 11 5 Summary of built ins e as al is 74 12 Example programs and programming techniques 75 12 1 Generating prime numbers aaau aaa e 75 12 2 PER T sehedullrig e nues bee ok aa pr ee UE PU kem G 76 12 3 Cryptarithmetic SEND MORE MONEY 78 12 4 Concurrent programming a it dr REL NS Ee dO 80 12 5 Encapsulated programming e 81 12 6 Classes and instances o o o 82 12 7 Using destructive assignment to calculate term size 83 128 Using a term as an array 84 12 9 MGMOIZATION ESA A RAE A d eua E rae e s 85 12 10 Method inheritance in the graphical interface toolkit 86 12 11 Structural constraints and arithmetic constraints 87 13 Fine points for would be wizards 88 13 1 Functional variables and apply ss 88 13 2 UBI IBVBIS 5 rcu A ode edo du PRSE ae DR UR De RC 89 13 3 Predicate and function positions 90 13 4 Compact sort definitions 92 19 5 SOM CNEOGING peri 5 8 ae ale oma Cert anon Rte pate SAEOR nt Gee lord tea 94 13 6 Printing convention 5 i a Ro eA RUE UR A eo ae RE de 94 14 Hints to write more efficient programs 95 14 1 Garbage collection och ci pr a NE Et RP Eo eed and 95 14 2 Residuos ls EGET oe E cae dn ie A 96 14 3 HPartlalevalldlo aa A Dar ede dO ehe tg 97 15 Compatibility with Prolog
203. tions It is meant as a public forum to answer questions and share programs and ideas It is not meant to report bugs although it may be used to ask public opinions about surprising behavior of Wild LIFE that may turn out to be a bug and to warn others against confirmed bugs life request prl dec com or life users request prl dec com These addresses are used to request to be put on or removed from the life users mailing list life bugstprl dec com When you strongly suspect a bug i e after reading the handbook and polling life users s opinion about the symptoms try to find the smallest self contained program that illustrates the bug and mail it to this address together with a script that shows the bug Research Report Draft March 1994 106 Hassan Ait Kaci et al E Manpage wild life 1 NAME wild lif interpreter for the LIFE language SYNTAX wild life options arguments DESCRIPTION LIFE Logic Inheritance Functions Equations is an experimental programming language with a powerful facility for structured type inheritance IFE reconciles styles from Functional Programming T the LIFE i O The Wild_Lif of applications dealing with complex data and Logic Programming by i automatic suspension mecha interpretation of rela specify structural depende he Wild_Life interpre language incremental query extension ilt in operations EE r is mplici
204. tly delegating control to an nism This allows interleaving tional and functional expressions which ncies on objects ter is a fully functional implementation of has a comfortabl rface with an extensive set user int It contains ability as well as an X Windows interface interpret specially suited for rapid prototyping It contains a tool for rapid building of interactive window based interfaces and a powerful preprocessor part o OPTIONS q Quiet mode The Wild_Life interpreter was originally developed as interface information messages allows Wild_Li startup fe to be minimal hassle output output trace informat is disabled Wild_Life w memoryN memory N Start up the system with N words of available memory memory is shared between data and programs w As ith the writ Forces completely silent operation banner Errors f the Paradise project at the DEC Paris Research Laboratory Its development is continuing in the Proteus project i e prompts variable values Yes No exit banner will be printed This used as an element of a Unix pipe with warnings trace messages program statement etc and file I O are still no user always errors and warnings are output to stderr ion to stdout which allows the user to inspect a misbehaving hen it is being used as a pipe element In verbose mode
205. turns the expression E and then proves the predicate G The latter is called by unification and hence if it is given one of the function s arguments that argument will be unified We illustrate the differences between unification and matching as calling mechanisms by means of a routine to append two lists We give three definitions of this routine as a function a predicate and using such that Here are the definitions Research Report Draft March 1994 28 9 append append CL TH L gt L IXI L1 L2 gt The standard predicate v append2 L L append2 X L1 L2 XI L3 A variant that matches i and unifies its third append3 L R true append3 X L1 L2 R gt tr Hassan Ait Kaci et al The standard functional version of append X appendl L1 L12 ersion of append append2 11 L2 L3 ts first argument R L ue R X L3 append3 L1 L2 1L3 The appenal function waits until its first argument is a list before returning its result The append2 predicate executes to completion immediately and unifies its result with its third argument Backtracking will provide alternate results The appena3 function uses such that It waits until its first argument is a list just like append1 and unifies its result with its third argument just like append2 The advantage of append3 over append is that tail recursion optimization is reg
206. unction 57 glb built in function 43 March 1994 154 global built in predicate 65 global constraint solving 87 global variable 60 quoting 65 glossary 103 grammar 58 110 graph subsumption 88 graphical interface toolkit 130 box 130 button 134 colors 137 constructor 133 example file ex tools If 130 look 135 menu 134 object hierarchy 138 panel 133 slider 134 widget 137 greatest lower bound glb 10 43 94 green cut 15 halt built in predicate 56 Hanoi towers of example program 85 has feature built in function 39 hash table 11 13 Herbrand term 7 14 101 120 heresy 17 hierarchy 8 consistency 9 cyclic 9 of built in sorts 10 of graphical interface objects 138 highlighting 9C9 1 immediate update with assert 71 72 implicit position 11 implies built in predicate 38 import built in predicate 6 70 incompatible sorts 10 incremental query 4 inheritance 8 92 multiple 8 87 92 130 init see accumulator 119 initialization file 3 March 1994 Hassan Ait Kaci et al initrandom built in predicate 42 insert see accumulator 113 instance example program 82 int built in sort 9 integer part floor 41 interpret symbols see accumulator 114 interrupting execution 6 inv see accumulator 117 invertibility of functions 19 87 1s see accumulator 112 is 2 built in Prolog 17 1s function built in function 47 is persistent
207. using a subsort of box t box It has the following features t box h space gt HSpace v Space VSpace text gt Text font id gt Fid Text The text appearing in the box VSpace The fotal amount of vertical space reserved around the text HSpace The total amount of horizontal space reserved around the text Fid The font ID used Default is bold see below for an explanation of font IDs If no size is already given for a box and if it is a subtype oft box then its size is computed according to Text Fid VSpace and HSpace H 2 5 Creating a box In order to be displayed and to work a box has to be created create box Box calls the constructor of Box if itis a subsort of a constructor and the drawing routine if the box is a subsort of a look sort If a box contains other boxes you only need to call create box for the parent box the call is propagated to the boxes children create box must be called only after all positioning constraints have been declared It is in fact possible to separate completely the positioning and the creation create box may be called several times with the same argument Later calls than the first will have no effect H 3 Main constructors H 3 1 Panels e panel c A panel c consists of a top level window containing widgets Features optional panel c title Title Title title of the window and icon Beware the positions of top level windows are usu
208. vel For serious development work it is recommended that you put your programs in modules and load them with the command import filename The Wild LIFE system comes with a large number of example programs each of which is defined in a separate module This allows example programs to be loaded in the same session without affecting each other or any other programs that may be loaded See for example the cryptarithmetic program of Section 12 3 9 load is neither Prolog s consult nor reconsult although it comes closest to consult If a file being loaded attempts to redefine an already defined object whose definition may not be extended then an error is reported As a result you will have to exit Wild LIFE and restart it when you need to reload a file 3 5 Interrupting execution If execution of a query goes into an infinite loop or takes too long to compute you may interrupt it by typing CTRL C There might be a slight delay if a garbage collection was taking place When the interrupt is dealt with the following prompt appears Command q c a s t h Each letter is a mnemonic shorthand for a command corresponding to a specific action to be taken for Wild LIFE at this point Hence typing h or in response to this prompt will yield the following to be printed Quit q Continue c Abort a Step s RETURN Trace t Help h Command q c a s t h Typing q will make Wild LIFE exit the session c wil
209. xtension 2 kKkK Yes X a Level stays at 2 because the second disjunct b b c c succeeds but creates a choice point Finally we type to pop to top level 2 gt 13 3 Predicate and function positions Wild LIFE makes a syntactic distinction between a predicate position and a function position A predicate position is any place in a program where the interpreter expects to find a predicate This includes at the query prompt in a clause body and certain arguments of the built ins call once such that and cond Similarly a function position is where the interpreter expects to find a function This includes all arguments of predicates and functions and all function bodies In the simplest case predicates are used only in predicate positions and functions are used only in function positions In general a predicate position may contain any term that will eventually be bound to a predicate or to one of the sorts true or false When the term is bound to a predicate then that predicate is executed When the term is bound to t rue then execution succeeds When the term is bound to false then execution fails If the term is incompatible with these three possibilities then an error is reported If the term is compatible with these three possibilities but it is not yet known which holds then the predicate position residuates It follows that predicate execution is order independent the same result is obtained for a pure pr
210. y be used to implement an efficient way of finding the list of moves needed to solve the Hanoi towers problem This example is adapted from The Art of Prolog 19 Research Report Draft March 1994 86 hanoi 1 A B C A B hanoi N in N 1 hanoi N 1 A C B Moves1 hanoi N 1 C B A Moves2 asserta hanoi N A B C Moves write Solved problem for N nl t A B C Moves append Moves1 A Hassan Ait Kaci et al B Moves2 t N The effect of using asserta is that solutions of intermediate problems are remembered This technique is often called memoization gt hanoi 3 M Solved problem for N 2 Solved problem for N 3 Yes M _A _B A C By A B CA C B _A _B Sai 4 kKkK No gt listing hanoi hanor 3 Ay ByE _A _B L A C B C B _C _Al C B A B hanoi 25 hy _B _C _A _C A B C B AS hanoi 1 A B QG A B succeed hanoi A int B C D E append _F _B _C _G cA CU hanoi _A Ll B DC F hanoi A 1 D C B G asserta hanoi A B C D E mi write Solved problem for A ml kKkK Yes Because hanoi is first called with _ the most general sort for the tower names it stores the most general solution for each value of N
211. ying code 74 concurrent programming 17 concurrent programming example pro gram 80 cond built in function 34 conjunction 34 cons built in sort 9 consistent sort ordering 9 constrained sort definition 30 example 76 resemblance to such that 30 March 1994 152 constructor see graphical interface toolkit 133 context accumulator 115 variable binding 4 52 copy pointer built in function 40 copy term built in function 40 coreference 7 coroutining 17 cos built in function 42 cosine 42 cpu time built in function 58 cryptarithmetic 78 current module 66 current module built in predicate 69 currying 17 22 argument consumption 24 difference with residuation 23 customization file 3 cut 15 34 green cut 15 scope 15 cycles in term 12 cyclic hierarchy 9 daemon 17 33 data driven programming 17 DCG accumulator 100 120 debugging abort to top level 6 56 accumulators 124 breakpoints 37 debugger tool in version 1 0 105 incremental query 4 interrupting execution 6 listing a program 55 pitfalls of self modifying code 74 run time statistics 56 single stepping 6 56 tracing execution 6 54 56 use of constrained sorts 33 use of daemons 33 use of display modules 71 use of display persistent 66 March 1994 Hassan Ait Kaci et al use of residuate 37 verbose mode 55 declarative language 1 declared sort 14 29 47 92 94 name space 18 Definit
212. zation 86 method inheritance 86 multiple inheritance 87 PERT scheduling 76 prime numbers 75 SEND MORE MONEY 78 sieve of Eratosthenes 84 subtyping of lists 30 term size calculation 83 using a persistent term 83 exclusive or 43 execution order 19 exists file built in predicate 54 exp built in function 42 expand load built in predicate 59 expander see accumulator 109 exponential 42 expose event 129 Extended DCG EDCG 110 extending built in sorts 10 eyes 9C9 1 Research Report Draft 153 factorial 18 fail built in predicate 34 false built in sort 9 FCP Flat Concurrent Prolog 80 feature 7 name space 18 selection 38 features built in function 39 finite domains 79 first order term 7 flexible record 7 floor built in function 41 freeze 17 96 function 17 actual arguments 18 boolean function 18 currying 22 definition 17 formal arguments 18 in a predicate position 18 matching 21 missing arguments 22 modify calling arguments 27 name space 18 60 66 operational semantics 19 passive constraint 78 position 90 programming style 25 quoting 26 use as sort 20 result is a predicate 18 rule 17 variable arity 56 functional expression 18 functional variable 88 garbage collection 56 61 74 95 Gaussian elimination 88 gc built in predicate 56 generate and test 17 genint built in function 42 get built in predicate 48 getenv built in f

Download Pdf Manuals

image

Related Search

Related Contents

Trampoline, actrice de la lutte contre l`illettrisme Les problèmes d  F-OIAN    GUIDE D`INSTALLATION BT-62110C Baignoire balnéo  Centralina remota a 12 elettrovalvole - Pan  Lexmark 5060-2XX User's Manual  Sonomètre numérique - Extech Instruments  Graco 332101A User's Manual  Broan 15WH Specifications  Olympus SP-310/SP350 User's Manual  

Copyright © All rights reserved.
Failed to retrieve file