PROLOG LAB Using visual PROLOG v

Document Sample
PROLOG LAB Using visual PROLOG v Powered By Docstoc
					       6.0 PROLOG LAB
Using visual PROLOG version 5.2
  Example 1: Assume the following
  “likes” facts knowledge base
  likes (ali, football).
  likes (ali, tennis).
  likes (ahmad, tennis).
  likes (ahmad, handball).
  likes (samir, handball).
  likes (samir, swimming).
  likes (khaled, horseriding).
      To represent the likes facts in
               VPROLOG A sequenceimplemented

•   FileNew                              as a pointer to an entry in
•   Then in the predicate section write the          a hashed symbol-table,
    declaration of the used predicates:              containing strings. The
PREDICATES                                           syntax is the same as for
nondeterm likes (symbol,symbol)                      strings.
• Then in the clauses section write the facts:
likes (ali,football).              defines non-deterministic
likes (ali,tenis).                 predicates that can backtrack
likes (ahmad,tenis).               and generate multiple
likes (ahmad,handball).            solutions. Predicates declared
                                   with the keyword nondeterm
likes (samir,handball).
                                   can fail and, in this case, do
likes (samir,swimming).            not produce any solution.
likes (khaled,horseriding).
    1. Queries as goals in PROLOG
•   To supply a query in PROLOG put it in the goal
    section as follows:
likes (ali, football).
• Then press Cntrl+G
The output will be Yes or No for concrete questions
1. Concrete questions: (queries without variables)
likes(samir, handball).            Yes
Likes (samir,football).            No
     2. Queries with variables
• To know all sports that ali likes:
• To know which person likes teniss
likes (Who,tenis).
• To know who likes what (i.e all likes facts)
likes (Who,What)
   3.Compound queries with one
1. To list persons who likes tennis and
    football, the goal will be
likes( Person, tennis ),likes (Person, football).

2. To list games liked by ali and ahmad
likes (ali,Game),likes (ahmad,Game).
  4-Compound queries with multiple
• To find persons who like more than one game:
likes(Person, G1),likes (Person,G2),G1<>G2.
• To find games liked by more than one person:
likes (P1,Game),likes(P2,Game),P1<>P2.
   5. Facts containing variables
• Assume we add the drinks facts to the likes
  database as follows:
drinks(symbol, symbol)
drinks(ali, pepsi).
drinks (samir, lemonada).
drinks (ahmad, milk).
• To add the fact that all persons drink water:
drinks (Everyone, water).
• If we put a goal like:
drinks (samy,water).
                                   The answer will
drinks (ahmad,water).              be: yes
• Rules are used to infer new facts from
   existing ones.
• A rule consists of two parts: head and
   body separated by the symbol (:-) .
• To represent the rule that express the
   facts that two persons are friends if they
   both like the same game:           Rule‟s
friends( P1,P2):-
            likes (P1,G),likes (P2,G),P1<>P2.
The head of
  the rule
                       The body of the rule
  7.Backtracking in PROLOG
      • For PROLOG to answer the query :
      friends (ali, P2).
      PROLOG will do the following matches and backtracking to
          the friends rule:

P1    G             P2           P1<>P2       friends (ali,P2)

ali   football      ali          false        fail

ali   tennis        ali          false        fail

ali   tennis        ahmad        true         succeed
         8.The domains section in
• It is used to define domains other than the built-
   in ones, also to give suitable meanings to
   predicate arguments.
• For example to express the likes relation:
likes(person, game)                  Person and game are
                                             unknown domains(error)

We should first declare person in the domains
   section as follows:  This declaration will allow prolog to detect
domains                 type errors.
                        Example: the query
person,game= symbol likes(X,Y), likes(Y,Z)
predicates              will result in a type error, because Y will be
                        matched to a game constant and can not
likes (person, game)    replace a person variable in the second sub
          9. Built-in domains
domain       Number of bits    range
short        16 bits           -32768..32767
ushort       16 bits           0..65535
long         32 bits           -2147483648..
ulong        32 bits           0..4294967295
integer      16 bit platform   -32768..32767
integer      32 bit platform   -2147483648..
byte         8 bits            0..255
word         16 bit            0..65535
dword        32 bit            0.. ..4294967295
         10. Basic standard domains
Domain        description

char          8-bits surrounded by single
              quotation: „a‟
real          Floating point number:
              42705, 9999, 86.72, 911.98e237
              Range 1e-307..1e+308
string        Pointer to 0-terminated byte arraey
              telephone, “Telephone”,t2,”T2”
symbol        As strings but implemented as a
              pointer to hashed symbol
              tablefaster than strings
   11. How to do arithmetic operations
                     Note:The compound goal:
                     multnum(7,5,X),addnum(X,X,Answer). Will
S=X+Y.               result in
multnum(X,Y,P):-     X=35, Answer=70
If the goal is:
Addnum(5,7,X).                  X=12
Multnum(5,7,X).                  X=35
12. More programs to test domains
• The isletter(X) predicate gives yes if X is a letter:
isletter(Ch):- To test this program, give it the following goals:
               a-       isletter(„x‟).           yes
„a‟<=Ch,       b-       isletter(„2‟).           no
Ch<=„z‟.       c-       isletter(“hallo”).       type error
               d-       isletter(a).             Type error
isletter(Ch):- e-       isletter(X)              free variable message
13. Multiple arity predicates overloading

• The arity of a predicate is the number of
  arguments that it takes.
• You can have two predicates with the
  same name but with different arities.
• You must group different arity versions of
  a given predicate name in both the
  predicate and clauses sections.
• The different arities predicates are treated
  as different predicates.
  14. Example: for multiple arity predicates
nondeterm father (person)
nondeterm father (person, person)
                         Anonymous variable can match anything.
father (Man):-                       A person is said to be a
                                     father if he is a father of
  father (Man,_).                    any one.
father (ali, ahmad).
father (samy, khaled).
15. A complete expert system that decides
how a person can buy a car.
• Assuming
  – A person is described by the two relations:
  salary (person, money)
  savings (person, money)
  – A car for sale is described by the two relations:
  cash (cartype, money)
• A person can buy a car
-with cash money if one third of his savings
   is greater or equal to the cash price of the
-with takseet if one third of his salary is
   greater or equal to the price of the car in
   case of cash divided by 30.
- If the person can buy a car using cash or
   takseet the system will advice him to buy
   with cash
     The VPROLOG program
person, car =symbol
salary (person, money)
savings (person, money)
cash (car, money)
takseet (car, money)
canbuy (person, car,way)
howcanbuy (person, car,way)
cash (cressida,15000).
cash (camri,55000).
cash (caprise82,5000).
cash (caprise90,8000).
cash (landcruizer2003,100000).
takseet (Car, TPrice):-
cash (Car, Price), TPrice=Price*1.2.
canbuy ( Person, Car, “cash”):-
savings (Person, M), cash( Car, N), M/3>=N.
canbuy ( Person,Car, “takseet”):-
salary (Person, M), takseet(Car,T),M/3>=T/30.
howcanbuy (Person,Car,Way):-
canbuy (Person,Car,Way),Way="cash";
canbuy (Person, Car, Way), Way="takseet",
  NOT(canbuy (Person,Car,"cash")).
Should be placed
around expressions
which include only   These variables will be bounded before
constants and /or    reaching the “not” expression containing
bounded variables.   them
      16. Controlling Backtracking
• The fail Predicate:     DOMAINS
• V Prolog begins
  backtracking when
                          nondeterm father(name,name)
  a call fails.
• The fail predicate is
  used to force
                          father (ali, salem).
                          father (ahmad, ibrahim).
• The following
                          father (ahmad, zaynab).
  program uses fail to
  get all solutions.
                          father (X,Y), write (X,” is ” ,Y,”‟s father\n” ),
• Without fail we will    fail.
                                                 To make the goal
  get only one            everybody.            succeed at the end
  solution.               GOAL everybody.
• Preventing backtracking by the cut (!)
• It is impossible to backtrack across a cut.
• Green cut: it is a cut used to prevent
  solutions which does not give meaningful
• Red cut : it is a cut used to prevent
  alternate subgoals.
• Example: to prevent backtracking to
  previous subgoals:
                   Only first solution to a and b is
r1:- a, b, !, c.   considered with many solutions for c
                 this clause for r1 will not be considered if a
                 solution is found in the above rule.
17. Highway Map modelling and recursive rules
• To represent the shown map we             a       4           b
  use the predicate
link ( node, node, distance)                                        5
                                            c           6
• To find a path from s to d
   – get it from mentioned facts :                                  g
   path (S,D, TDist):-link (S, D, TDist).           d

   – Or find a node x which has a link      link(a,b,4).
     from S to X and a path from X to D     link (a,c,2).
     as follows:        Total distance
                                            link (b,g,5).
   path (S,D, TDist):-                      link (c ,g,6).
     link (S,X,DS1),path (X,D,DS2),         link (c,d,5).
     TDist=DS1+DS2.                         link (d,g,3).
                         The complete path distance finder program
distance= integer
nondeterm link (node, node, distance)
nondeterm path ( node, node, distance)
link (a,c,2).
link (b,g,5).                 Facts that model the
link (c ,g,6).                     road map
link (c,d,5).
link (d,g,3).                                         Recursive
path (S,D, TDist):-link (S, D, TDist).                  rule
path (S,D, TDist):-
    link (S, X, TD1 ),path (X,D,TD2), TDist=TD1+TD2.
GOAL                                       TotalDistance=9
path (a, g, TotalDistance).      output    TotalDistance=8
                                         3 Solutions
18. Rules which behave like procedures
• A rule that when its             greet:-
                                   write(“ASalamo Alykom”),n1.
  head is found in a
  goal will print
  something.           PREDICATES
• Rules used like      nondeterm action (integer)
  case statements: action(1):- nl, write (“N=1”),nl.
                       action(2):- nl, write (“N=2”),nl.
Only rules with        action(3):- nl, write (“N=3”),nl.
                       action (N):- nl,
  matching             N<>1,N<>2,N<>3,write (“N=?”),nl.
  arguments will be GOAL
                       write (“Type a number 1->3”), readint (N) ,
  executed, others action(N).
  will be tested but
  will fail.
• Since rules that PREDICATES
  has unmatched nondeterm action (integer)
  arguments will CLAUSES
  be tested and
                   action(1):-!, nl, write (“N=1”),nl.
  will fail. This
  will slow the    action(2):- !,nl, write (“N=2”),nl.
  program. To      action(3):- !,nl, write (“N=3”),nl.
  speed up the action (_):- nl,
  system use the ,write (“unknown number ?”),nl.
  cut as shown. GOAL
                     write (“Type a number 1->3”), readint (N)
                     , action(N).
• If you want to
  test a range x>5
  and <9 place
  the cut after the
  test sub goals.         Action(X):- X>5,X<9,!,write(“5<N<9”),n1.
  To make a rule return a value
• To define a rule which classifies a number either
   positive, negative or zero:
nondeterm classify (integer,symbol).
classify( X,pos):- X>0.
                              What carries
classify( X,neg):- X<0.       the returned
classify( X,zero):- X=0.         result
Classify ( 5,What)
Classify (-4,What)                         What=nig

Classify (X,What)                           error
   19. Compound data objects
• Compound data objects allow you to treat
   several pieces of information as a single
   item (like structures in c, c+, or c#).
• Example: to represent a date object:
DOMAINS                called : functor

date_cmp= date(string, unsigned, unsigned)
Hence in a rule or goal you can write:
Here D will be treated as a single item.
• The arguments of a compound object can
  themselves be compound:
Example : to represent the information for
  the birthday of a person:-
              BIRTHDAY             birthday= birthday (person,
                                   person = person (name,
    PERSON               DATE
                                   date= date (day, month, year)
                                   name, month =string
Ahamd   Ali     1   March   1960   day, year= unsigned

     19.1 A family birthday program
person = person (name, name)
birthdate= bdate (day, month, year)               Compound
name, month =string                                 objects
day,year= unsigned
nondeterm birthday (person, bdate)
                            Lists all birthday‟s person, and date objects
%birthday(X,date(_,"March",_)).             Lists persons born on March

Lists persons whose second name is “mohamd” with year of birth
DOMAINS            19.2 Using system date
 person = person (name, name)
 bdate= bdate (day, month, year)
day ,month, year= unsigned
nondeterm birthday (person, bdate)
testnow (unsigned, bdate)
get_birth_thismonth:- date (_,Thism ,_), write ( “now month is", Thism), nl, birthday (P, D),
    testnow(Thism, D), write_person(P), fail.
get_birth_thismonth:-write (“Press any key to continue"), nl, readchar(_).
testnow(TM,bdate (_,BM,_)):- TM=BM.
write_person(person(Fn, Ln)):-write(" ", Fn, "\t\t ", Ln), nl.
GOAL get_birth_thismonth.
     19.3 Using alternatives in domain declaration
• Assume we want to declare the following statements:
   – Ali owns a 3-floar house
   – Ali owns a 4-door car
   – Ali owns a 3.2 Ghz computer
   – To define a thing to be either house, car, or computer:
thing= house( nofloars); car (nodoors); computer(ghertz)
ghertz=real                            Use or(;) to separate
person= person(fname, lname)
fname, lname=symbol                         goal
PREDICATES                                  owns (P,X).
nondeterm owns(person, thing)               2 solutions
owns( person(mohamad, ali), house(3)).
                          19.4 Lists
• To declare the subjects                            Here, the teacher name
  a teacher might teach:                             is repeated many times.
                                                     We need a variable
                                                     length data structure that
teacher (symbol, symbol, symbol)                     holds all subjects that a
CLAUSES                                              teacher can teach

teacher (ahmad, ezz,cs101).                      Solution use a list data
                                                 Solution: use a list data
                                                 structure for the subject
teacher (ahmad, ezz, cs332).                     structure for the subject
teacher (amin, mohamad, cs435).
teacher (amin,mohamad, cs204).            subject=symbol *
teacher (amin,mohamad, cs212).            PREDICATES
teacher (reda, salama, cs416).            teacher (symbol,symbol,subject)
teacher (reda, salama,cs221).             teacher(ahmad, ezz,[cs101,cs332] )
teacher (amin,mohamad, [cs204, cs435, cs212] ).
teacher (reda,salama, [cs416, cs221] ).
   20. Repetition and Recursion
• Repetition can be expressed in PROLOG
  in procedures and data structures.
• Two kinds of repetition exist in PROLOG:

Backtracking: search for multiple solutions   Recursion: a procedure calls itself

When a sub goal fails,
PROLOG returns to the most
recent subgoal that has an            Normal recursion:      Tail recursion: fast
untried alternative.                                         and less memory
                                      Takes a lot of
Using the fail predicate as the       memory and time        Compiled into
end of repeated subgoals we                                  iterative loops in
enforce PROLOG to repeat                                     M/C language
executing different alternatives
of some subgoals.
      20.1 Repetition using backtracking
      •Example: Using fail
                                country(X)   write   nl   fail print_co
      to print all countries:                (X)               untries
nondeterm country (symbol)      X=“Egypt” ok         ok fail fail
country (“Egypt”).              X=“SaudiA ok         ok fail fail
country (“SaudiArabia”).
country ( “Seria”).             rabia”
country (“Sudan”).
print_countries:- country(X),
          write(X), nl, fail.
                                X=“Seria”    ok      ok fail fail
                                X=“Sudan” ok         ok fail fail
•To do pre-actions
(before the loop )or
post-actions (after the        20.1.2 Pre and post actions
loop), write different
versions of the same                 country(X)         write(X, ”      fail   Print_cou
predicate.                                              and “)                 ntries
•   nondeterm country
                                     X=“Egypt”          Ok              fail   fail
•   nondeterm print_countries
•   CLAUSES                          X=“SaudiArabia”    Ok              fail   fail
•   country ("Egypt").
•   country ("SaudiArabia").
•   country ( "Seria").              X=“Seria”          Ok              fail   fail
•   country ("Sudan").
•   print_countries:-
•     write("Some Arabic             X=“Sudan”          Ok              fail   fail
    countries are"),nl,fail.
•   print_countries:-
    country(X), write(X," and "),
    fail.                                                            Pre-action
•   print_countries:-
•   nl, write("there are others"),
                                        Some Arabic countries are
    nl.                                 Egypt and SaudiArabia and Seria and Sudan
•   GOAL                                There are others
•   Print_countries.
                 Main-action                                         Post-action
20.2 Implementing backtracking with loops
• The following repeat           PREDICATES
  predicate tricks               repeat
  PROLOG and makes it            typewriter
  think it has infinite          CLAUSES
  solutions:                     repeat.
                                              Nth solution
repeat.              solution
                                  (N+1)th solution
                                 repeat:- repeat.
repeat:- repeat.      2nd        trypewriter:-        Multiple
                      solution                        solutions attract
The shown program uses           repeat,              backtracking
                                                      when fail occurs
  repeat to keep                 readchar(C),
  accepting a character          write(C) ,
  and printing it until it is    C=„\r‟,! .   /* if CR then cut
          20.3 Recursive procedures
• To find the factorial of a
  number N : FACT(N)
                               factorial (unsigned, real)
IF N=1 then FCT(N)=1
                               factorial (1,1):-!.
                               factorial (N, FactN):-
   FACT(N)=N* FACT(N-1)
• Using PROLOG, the            factorial (M, FactM),
  factorial is implemented
  with two versions of the
  factorial rule as shown
                               factorial (5,F).
                               1 Solution
                        20.4 Tail Recursion
•        Occurs when a procedure calls itself as the last step.
•        Occurs in PROLOG ,when
           1. The call is the very last subgoal in a clause.
            2.   No backtracking points exist before this call.
            3.   The recursive predicate does not return a value.
            4.   Only one version of this predicate exists.
•        Example:
count (N):-                             No alternative
                                      (2)Noalternative solutions exist
                                          No alternative
write(N), nl,                           solutions backtracking points
                                       here no here
                                         solutions here

NewN=N+1,                   (3)N is bound to a constant value and no other free
                            variable no return value
count (NewN).
GOAL                       (1) Last call no need to save state of the previous
                           call stack is free no extra memory is needed
count(0).                  small memory and fast due to no need to push state
    You can use a
    cut(!) before the   Write numbers from 0 to infinity ( will get unexpected values
    last call to be     due to overflow)
    sure of (2).
20.5 Using arguments as loop variables
 • To implement           PREDICATES
    factorial with        factorial (unsigned, long)
    iterative procedure   factorial_r(unsigned, long, unsigned, long)
    using C-language:
 long fact;               CLAUSES
 long p=1;                factorial (N, FactN):-           arguments I,P
 unsigned i=1;            factorial_r(N, FactN,1,1).
 while(i<=n)              factorial_r( N, FactN, I, P):-
 {                        I<=N,            Test end condition to go to
 p=p*i;                   !,               other version if not satisfied.
                          NewP=P*I,          To prevent backtracking and
 }                                           to allow tail recursion.

                          factorial_r(N, FactN ,I ,P):- I>N, FactN=P.
         21. Lists and Recursion
• List processing allows handling objects that
  contain an arbitrary number of elements.
• A list is an object that contains an arbitrary
  number of other objects.
• A list that contains the numbers 1,2 and 3 is
  written as [1,2,3] .
• Each item contained in a list is know as an
• To declare the domain of a list of integers:
  – Domains
                                         Means list of integers
  – intlist= integer *

       Could be any other name ( ilist, il,…)
• The elements of a list must be of a single
• To define a list of mixed types use compound
  objects as follows:
• Domains
  – elementlist= element *
  – element=ie (integer); re ( real); se (string)
• A list consists of two parts:
  – The head : the first element of the list
  – The tail : a list of the remaining elements.
• Example: if l=[a,b,c]  the head is a and the
  tail is [b, c].            The Tail
                  The Headt
• If you remove the first element from the tail of
   the list enough times, you get down to the
   empty list ([ ]).
• The empty list can not be broken into head and
• A list has a tree structure like compound objects.
• Example: the tree structure of
 [a, b,c, d] is drawn as shown           list

 in the figure.                               lista
Note : the one element list [a] is not as the
element a since [a] is really the compound data   b   list
structure shown here
                                  [a]             c    list
                     a                []          d     []
          21.1 List processing
• Prolog allows you to treat the head and tail
  explicitly. You can separate the list head
  and tail using the vertical bar (|).
• Example :
•     [a,      b,   c          ]
     ≡[a | [b,      c        ] ]
     ≡[a | [b|      [c ] ] ]
     ≡[a | [b|      [c| [] ] ] ]
     ≡[a , b|       [c ]       ]
      • 21.2 List unification: the following table
        gives examples of list unification:

list1          list2               Variable binding
[X, Y, Z]      [ book, ball, pen ] X=book, Y=ball, Z=pen

[7]            [X|Y]               X=7,Y=[ ]
[1, 2, 3, 4]   [X, Y|Z ]           X=1,Y=2,Z=[3,4]
[1,2]          [3|X]               fail
• 21.3 Using lists
   – Since a list is really a
     recursive compound data               list= integer *
     structure, you need
     recursive algorithms to               PREDICATES
     process it.                           write_a_list( list ) Do nothing
   – Such an algorithm is                  CLAUSES
                                                                 but report
     usually composed of two                                     success.
     clauses:-                             write_a_list([ ]).
      • One to deal with empty list.T=[ ]
                                          write_a_list ( [ H | T ] ):-
      • The other deals with
        ordinary list (having head        write(H),             Write the
        and tail).                                              head
• Example: the shown                      nl,
  program writes the                       write_a_list( T).     Write the
  elements of an integer list.                                   Tail list

                                           write_a_list([ 1, 2, 3]).
21.4 Counting list elements                DOMAINS
•   Two logical rules are                  list= integer *
    used to determine the
    length of a list                       PREDICATES
      1. The length of [ ] is              length_of ( list, integer)
         0.                                CLAUSES
      2. The length of the                 length_of ( [], 0).
         list [X|T] is 1+the
         length of T.              T=[ ]
•   The shown Prolog                Length_of ( [ H | T ],L ):-

    program counts                  length_of ( T ,M ),

    the number of                   L=M+1.
    elements of a list              GOAL

    of integers (can be             length_of([ 1, 2, 3],L).

    used for any       Homework: modify the length program to
    type).             calculate the sum of all elements of a list
          21.5 Modifying the list
• The following
  program adds 1 to            list= integer *
  each element of a            add1 ( list, list)
  list L1 by making            CLAUSES
                               add1 ( [], []).
  another list L2:
  – If L1 is [ ] then L2=[ ]   add1 ( [ H1 | T1 ],[H2|T2] ):-
  – If L1=[H1|T1]              add1( T1,T2).
    assuming L2=[H2|T2]        GOAL
                               add1( [ 1, 2, 3], L ).
     • H2=H1+1.
     • Add 1 to T1 by the                  L=[ 2, 3, 4]
       same way
21.6 Removing Elements from a list
• The following
  program removes              DOMAINS
                               list= integer *
  negative elements            PREDICATES
  from a list L1 by            discard_NG ( list, list)
  making another list          CLAUSES
  L2 that contains non         discard_NG ( [], []).
  negative numbers of          discard_NG ( [ H1 | T1 ],L2 ):-
  L1 :                         H1<0,
  – If L1 is [ ] then L2=[ ]   !,
  – If L1=[H1|T1] and
    H1<0 then neglect H1       discard_NG ( [ H1 | T1 ],[H1|T2] ):-
    and process T1             discard_NG(T1,T2).
  – Else make head of L2       GOAL
    H2=H1 and Repeat           discard_NG( [ 1, -2, 3], L ).
    for T1.
                                                L=[ 1, 3]
             21.7 List Membership
• To detect that an                DOMAINS

  element E is in a list           namelist= name*
                                   name= symbol
   – If L=[H|T] and E=H            nondeterm member (name, namelist)
     then report success           CLAUSES
   Else                            member (E ,[E | _ ] ).

   – search for E in T             member (E, [ _ | T]):-
                                    member (E,T).
 Try the goal
 member (X, [samy, salem,ali]).    GOAL
 What happens if we put a cut at   member (ali, [samy, salem,ali]).
 the first clause as follows:
 member (E ,[E | _ ] ):- ! .
  21.8 Appending one list to another
• To append L1 to L2                        DOMAINS
  we get the result in                      intlist= integer*

  L3 as follows                             PREDICATES

• Append (L1,L2,L3):                        append (intlist, intlist, intlist)
     – If L1=[ ] then L3=L2.
                                            append ([], L2,L2 ).
     – Else                                 append ([H | T1], L2,[H|T3] ):-
     – Make H3=H1                             append (T1, L2, T3).
     and                                    GOAL
     – make T3 =T1 +L2                      append([1,2,3],[5,6],L).
Try the goals:
1-append ([1,2],[3],L), append( L, L,LF).                L= [1,2,3,5,6].
2-append ( L,[5,6], [1,2,3,5,6]).
             21.9 Tracing the append goal
                                   L =[1,2,3,5,6]        DOMAINS
                                                         intlist= integer*
append ([1 | [2,3] ],[5,6], [1|T3] ):-

append ([2,3 ],[5,6], [T3] ):-      T3 =[2,3,5,6]        append (intlist, intlist, intlist)
 append ([2 | [3] ],[5,6], [2|T3‟] ):-
                                                         append ([], L2,L2 ).
                                                         append ([H | T1], L2,[H|T3] ):-
 append ([3 ],[5,6], T3‟ ):-             T3‟ =[3,5,6]
                                                           append (T1, L2, T3).
append ([3 | [ ] ],[5,6], [3|T3‟‟] ):-                   GOAL
    append ([ ],[5,6], T3‟‟ ).             T3‟‟ =[5,6]
                                                                    L= [1,2,3,5,6].
     22 VPROLOG facts Section
•  The facts section is declared to allow a
   programmer to add or remove facts at run time.
• Facts declared in fact section are kept in tables
   to allow modification, while normal facts are
   compiled into binary code for speed
1. To declare a fact in a fact section:
                          Name of this
• person=string           fact section
• FACTS -up
• father (person, person)
• father (“samy”, “ali”).
    22.1Updating the facts section
• To add a fact to the facts section use
• asserta or assert to insert the new fact
  at the beginning of the fact section
                               Will be added before the fact
• Example:                         :father (“samy”, “ali”).

   – asserta( father(“ali”,”ahmad”)).
• assertz to add the fact at the end of its fact
                               Will be added after the fact:
  section.                         father (“samy”, “ali”).

   – assertz( father(“ahmad”,”khalil”)).
                                                X=ali, Y=ahmad
If we execute the goal father ( X,Y).,          X=samy, Y=ali
                                                X=ahmad, Y=khalil
 The output will be as shown here:
• There is no automatic check in VPROLOG
  if you insert a fact twice, to prevent this
  you can declare the following predicate
  which tests a fact before adding it as
• PREDICATES                    Search for the fact
                                if found break
• uassert(up)                   Else assert it

uassert (father(F,S)):- father(F,S), ! ;
 assert (father(F,S)).
    22.2Saving and loading facts.
• To save the facts in a            person=string
                                    FACTS - up
  file you can use the               father (person, person)
  save predicate as                 uassert (up)
  follows:                          addfathers
save (filename).                     CLAUSES
                                    father ("samy", "ali").
    Or                              uassert (father(F,S)):- father(F,S), ! ;
Save (filename, factsectionname).    assert (father(F,S)).

• To load a fact                    repeat.
  database use                      repeat:- repeat.

  consult as follows:               addfathers:- repeat,readln (F),readln (S),
consult (filename,                  uassert(father(F,S)),F="",!,save("c:\\facts",
   factsectionname).                up).

                                    addfathers, father(X,Y).
                 Removing facts
• To remove a fact use the predicate retract as
   retract(<the fact>[,factsectionname]).
• Example to remove the fact father(“samy”,“ali”):
• To remove all facts about “samy” as a father:
   retract (father(“samy”,_)).
   Note: the previous program adds a father whose name
     is null, to remove all facts that has a null string name
     modify the add father predicate as follows:
addfathers:- repeat,readln (F),readln (S),
  uassert(father(F,S)),F="",!, retract(father(F,S)),
                                   To remove the last entered fact
                                          with null strings

Shared By: