Prolog_LabSheet

Embed Size (px)

Citation preview

  • 7/26/2019 Prolog_LabSheet

    1/34

    LAB#1UNDERSTAND BASIC OF PROLOG

    Getting computers to communicate with us in human languages like English, either by printing on acomputer terminal, understanding things we type on a computer terminal, generating speech, orunderstanding our speech (natural language);

    Getting computers to remember complicated interrelated facts, and draw conclusions from them.

    If we want computers to act intelligent, we must help them. We must tell them all the commonsenseknowledge. ow there are many different kinds of knowledge. Without getting deep into philosophy(or specifically epistemology, the theory of knowledge), there are two main kinds! facts and reasoningprocedures. "acts are things true about the world, and reasoning procedures (or inferences) are ways tofollow reasoning chains between facts. #ince facts are easier to represent than procedures.

    $he program logic of %rolog is e&pressed in terms of relations, represented as facts and rules. 'computation is initiated by running a queryoer these relations.

    HOW MANY FACTS DO WE NEED

    Infinity of facts is true about the world. ow then do we decide, which to tell a computer*Generally, we must decide that what we want from computer to do, then make sure to tell thecomputer eery fact that might be releant to that behaior. +ibraries- of useful facts for particularsubects will help. /ut smarter you want the computer to be, more facts you must tell it.

    SEMANTIC NETWOR!S

    %ictures can make a complicated set of facts a lot clearer. $here0s a simple pictorial way(labeled directed graph) to show the predicate e&pressions. We0e been discussing the semantic

    network. /ut there is one restriction on it! semantic networks can only directly represent predicatesof two arguments (so type predicate must be in two 1argument form).

    E"AMPLE

    a2kind2of(khaiber, ship).

    a2kind2of(tipu2sultan, ship).

    part2of(khaiber, pak2nay).

    part2of(tipu2sultan, pak2nay).

    part2of(pak2nay,pak2goernment).

    a2kind2of(pak2gornment,goernment).

    color (ship, gray).location(khaiber, 34n54e).

    has(pak2goernment, ciil2serice2system).

    1 | P a g e

  • 7/26/2019 Prolog_LabSheet

    2/34

    E"AMPLE OF SEMANTIC NETWOR!

    OB$ECT

    6raw a semantic network representing the following facts, and implement following fact using%rolog!

    #hips are things.

    7arriers are ships.

    #hips hae a position.#hips hae a crew.

    7arriers hae planes.

    %lanes are things.

    ' crew consists of people.%eople are things.

    2 | P a g e

  • 7/26/2019 Prolog_LabSheet

    3/34

    LAB#%

    TEST THE E&ALUATION OF GOALS' USING UNIFICATION AND

    BAC!TRAC!ING

    Unification is the process of matching two predicates and assigning free ariables to make thepredicates identical. $his mechanism is necessary so that %rolog can identify which clauses to call andbind alues to ariables. $hese are the maor points about matching (Unification) presented in thissession.

    When a new call is made, a search for a match to that call also begins at the top of the program

    When a call has found a successful match, the call is said to return, and the ne&t sub goal in turn canbe tried.

    8nce a ariable has been bound in a clause, the only way to free that binding is through backtracking.Backtracking is the mechanism that instructs %rolog where to go to look for solutions to the program.

    $his process gies %rolog the ability to search through all known facts and rules for a solution. $hereare four basic principles of backtracking gien in this session!#ub goals must be satisfied in order, from top to bottom.%redicate clauses are tested in the order they appear in the program, from top to bottom.

    When a sub goal matches the head of a rule, the body of that rule must be satisfied ne&t. $he body ofthe rule then constitutes a new set of sub goals to be satisfied.

    ' goal has been satisfied when a matching fact is found for each of the e&tremities (leae) of the goaltree.

    ' call that can produce multiple solutions is non-deterministic, while a call that can produce one andonly one solution is deterministic.

    E(a)*le 1

    factorial(9,3).

    factorial(:,) !:,?.

    De+,)*,-.t.,n /0a+t,r.al/'Fa+t22!

    :3 is 5, (:3 is @, (:3 is 3, (:3 is 9, (=A3), AA3 is :AA3 > =AA3), AA@ is :AA@ > =AA3), AAB is:AA5 > =AA@), AA@C is :AAC > =AAB)

    : is decreasing step by step

    Each has the alue of = form preious step.

    3 | P a g e

  • 7/26/2019 Prolog_LabSheet

    4/34

    E(a)*le %

    talks2about(',/)!

  • 7/26/2019 Prolog_LabSheet

    5/34

    y(engl

    and,5eL).c

    ountry(france,@.5eL).

    country(g

    5 | P a g e

  • 7/26/2019 Prolog_LabSheet

    6/34

    ermany

    ,3.BeL).cou

    ntry(denmark,@.CeB).co

    untry(can

    6 | P a g e

  • 7/26/2019 Prolog_LabSheet

    7/34

    ada,L.

    5eB).

    7 | P a g e

  • 7/26/2019 Prolog_LabSheet

    8/34

    LAB#3

    TO TEST A SIMPLE DISEASE DIAGNOSIS SYSTEM < A CASE STUDY

    go ! : > :, write(7),cube. F> calculate 7 and write it then ask again cube. >F

    Fun+t.,n%

    ealuate(E&pression, 'nswer !< 'nswer is E&pression).

    4uer5

    *< ealuate(@>N,'ns).'ns A 3Oes

    Fun+t.,n3

    L,,*- /e=u.8alent t, W7.le < D, l.>e C2 test!< repeat,

    write(H%lease enter a numberH),read(:),

  • 7/26/2019 Prolog_LabSheet

    9/34

    (:A!AC@).

    In this e&ample the program will ask you to enter a number until you enter C@.

    Fa?,na+.. Ser.e-

    go()!< write(9),nl, write(3),nl, go(9,3,).

    go(2,2,9)!< ?. go(',/,7)!< '3 is ',/3 is /,

    73 is '3P/3, write(73),nl, ew7 is 7e a rule 0,r generat.ng *al.n9r,)e nu)?er-

    3, 33, @@, 55, CC, 44, BB, LL, OO, NN, Q..

    LAB#@

    TO WOR! WITH THE IMPLEMENTATION OF PROLOG DATABASE /I;E;'

    FACTS AND RULES WHICH MA!E RELATIONAL DATABASE2

    6atabases in %rolog are bit different from other (procedural) databases. In %rolog there are two typesof databases! static databases and dynamic database.

    ' static database is one whose component0s (field records) information, as well as rules about theirrelationships is stored in memory at run time.

    ' dynamic database is composed of facts gathered by the user during program e&ecution. $hese factsre stored in a separate (dynamic) database. ' dynamic database is stored in memory along with a staticdatabase; more memory is needed here.

    ou can name facts section (which creates a corresponding internal domain). our program can haemultiple facts sections, but each one must hae a uniJue name.

    With the standard predicates assert, asserta, assertz, and consult, you can add facts to the facts sectionat run time. ou can remoe such facts at run time with the standard predicates. ou can remoe suchfacts at run time with the standard predicates retractand retractall.

    ou can sae predicates from facts0 section to a file and can consultor reconsultit in program. oucan create or edit such a fact file with an editor, and then insert facts from the file into your runningprogram with consult.

    ou can call database predicates in your program ust like you call other predicates.

  • 7/26/2019 Prolog_LabSheet

    10/34

    ou can handle facts as terms when using the domain internally, generated for a database section.It is simple to build Jueries using references and relationships.

    E&ample!

    #uppose department of an educational institute stores this information for each student.

    student number, last name, first name, street, city, state, maor, minor, class taken, time, class credit

    hours, class meeting time, class grade, total credit hours, total honor points, and honor point aerage adatabase system should be able to handle Jueries about any combination of fields pertaining to anindiidual student; which %rolog can do ery well. $he aboe attributes are diided into three relations(tables)! student, class, and maor, haing the formats following and with key fields indicated by allcapital letters.

    1 < NF OF DATABASE

    student( STUDENTNUMBER, ast2name, "irst2name, #treet2address, 7ity, #tate)class(CLASSNAME, STUDENTNUMBER, 7redit2hours, eeting2time, Grade)maor(STUDENTNAME, aor2subect, inor2subect)

  • 7/26/2019 Prolog_LabSheet

    11/34

    RECORDSstudent(1001, brown, sam, happy_way,marquette, mi).student(1022, andrews, andy, kin_olaf_st, marquette, mi).student(10, !ummings, maria, gray_rd, marquette, mi).student(2000, "ylon, fed, green#iew_a#e, lansing, mi).student($022, franklin, georgia, burrow_way, detroit, mi).

    student(%001, green, nan!y, green#iew_rd, mt_pleasant, mi).student(&000, green, sam, green#iew_rd, mt_pleasant, mi).student(&0&&, pershing, "ere"es, happy_way, marquette, mi).student('000, petersen, olaf, bla!kstone_bl#d, detroid, mi).student('0, sklarson, bill, !enter_bl#d, milwaukee, wi).student(001, timmons, timmy, twin_st, minneapolis, mn).student(&&&, young, !hiquita, felton_st, philadelphia, pa).student(00&, herring, !remora, briggs_bl#d, *etroit, mi).

    !lass(elem_math, 1001, $, m00).!lass(elem_math, 2000, $, m00).

    !lass(elem_math, %001, $, m00).!lass(elem_math, &&&, $, m00).!lass(elem_math, 00&, $, m00).!lass(intro_!omp, 1001, $, m1100).!lass(intro_!omp, 2000, $, m1100).!lass(intro_!omp, &000, $, m1100).!lass(intro_!omp, '0, $, m1100).!lass(intro_!omp, &&&, $, m1100).!lass(english_!omp, $022, %, t00).!lass(english_!omp, %001, %, t00).!lass(english_!omp, &000, %, t00).

    !lass(english_!omp, '000, %, t00).!lass(english_!omp, '0, %, t00).!lass(english_!omp, 001, %, t00).!lass(english_!omp, 00&, %, t00).!lass(intro_bus, 1001, $, t1200).!lass(intro_bus, %001, $, t1200).!lass(intro_bus, &000, $, t1200).!lass(intro_bus, '000, $, t1200).!lass(intro_bus, 001, $, t1200).!lass(intro_bus, &&&, $, t1200).

    ma+or(1001, business, e!onomi!s).

    ma+or(1022, business, e!onomi!s).ma+or(10, business, e!onomi!s).ma+or(2000, !omputer_s!i, math).

    ma+or($022, a!!ounting, business).ma+or(%001, business, a!!ounting).ma+or(&000, !omputer_s!i, bussiness).ma+or(&0&&, !omputer_s!i, e!onomi!s).

    ma+or('00', e!onomi!s, a!!ounting).

    ma+or('0, e!onomi!s, !omputer_s!i).

  • 7/26/2019 Prolog_LabSheet

    12/34

    ma+or(001, a!!ounting, e!onomi!s).ma+or(&&&, a!!ounting, business).

    ma+or(00&, e!onomi!s, a!!ounting).

    OB$ECTS

    1. ind the !omplete address (street, !ity, state) of student -am rown. ind thestudent number of student /ero"ed Pershin.

    2. ind laf Petersens ma+or and minor elds.$. 3ist the names o4 all students li#ing in 5i!higan (56).%. 3ist the student numbers of all 3ower Peninsula students (i.e., students li#ing in

    5i!higan, but not in 5arquette).&. 3ist the student numbers of all students taking elem_math. 3ist the names of

    all students taking elem_math.'. 3ist the names of all students with business as their ma+or eld.. 3ist the names and address of all students with e!onomi!s as their minor eld.

    . 3ist the names of all students taking a !lass at noon on 7uesdays (t1200).

    4UERIES FOR ABO&E OB$ECTS

    1. student(_, brown, sam, -treet, 8ity, -tate).student(-tudent_number, pershing "er"es, _, _, _).

    2. student(-tudent_number, petersen, olaf, _, _, _), ma+or(-tudent_number,

    5a+or, 5inor).$. student(_, 3astname, rstname, _, _, mi).%. student(-tudent_number, _, _, _, 8ity, mi), 8ity 9: marquette.

    Orstudent(-tudent_number, _, _,_ , 8ity, mi), not(8ity : marquette).

    &. !lass(elem_math, -tudent_number, _, _).!lass(elem_math, -tudent_number, _, _),student(-tudent_number,3astname, irstname, _, _, _).

    '. student(-tudent_number, 3astname, irstname, -treet, 8ity, -tate),ma+or(-tudent_number, business, _).

    . student(-tudent_number, 3astname, irstname, -treet, 8ity , -tate),ma+or(-tudent_number, _, e!onomi!s).

    . !lass(_, -tudent_number, , t1200),ma+or(-tudent_number, 3astname,irstname, _, _, _).

  • 7/26/2019 Prolog_LabSheet

    13/34

    LAB#

    TO UPDATE DELETE RECORDS ON RUNTIME USING ASSERT AND

    RETRACT;

    ake a fact file for updateF delete operations and consult it, then assert a fact which is beingused in the program which is to be updated i.e., class (2, 2, 2); at console to make it to use

    dynamically at run 1 time. $his operation defines a dynamic rule.

    E&ample!

    *< assert(class(3993, umer, g)).

    *< assert(class(399@, ali, g)).

    *< assert(class(3995, mariam, g)).

    *< assert(class(399C, Ria, g)).

    *< retract(class(3993,umer,g)).

    *< asserta(class(3994,ali,g)).

    *< retractall(class(2,ali,2)).

    OB$ECT

    assign_grade;nter -tudent?=s number; =),read(6*),nl,!lass(/,6*,@,A),

    write(=!urrent re!ord=),nl,write(=

  • 7/26/2019 Prolog_LabSheet

    14/34

    seeing(") F> " is unified with the name of the current input file. >Fseen F> 7loses current input stream. >F

    tell(") F> "ile " becomes the current output stream. >F

    telling(") F> " is unified with the name of the current output file. >Ftold F> 7loses the current output stream. >F

    close(") F> "ile ", currently open for input or output, is closed. >F

    rename(",) F> If file " is currently open, it is closed and renamed to . If is HSTH, the file is deleted. >F

    S,)e e(tra 0.le ,*erat.,n-

    delete2file

    rename2file

    siRe2file 7d

    make2directory

    delete2directory

    rename2directory

    E(a)*le 1

    seeing("ile)

    see("ile)

    read(6ata)

    seen

    "ileAHuserH will select the keyboard for the input source

    E(a)*le %

    browse("ile) ! sae for later >F

    see("ile), F> open this file >F

    repeat,read(6ata), F> read from "ile >F

    process(6ata),

    seen, F> close "ile >Fsee(8ld), F> preious read source >F

    ? F> stop now >F

    process(end

  • 7/26/2019 Prolog_LabSheet

    15/34

    LAB#

    TO USE PROLOG LISTS AND LIST MANIPULATION;

    L.-t C,n-tru+t.,n

    $he construction of a list is the reerse! take a ariable bound to any old list i.e., "r' e' 9and addthe element, say, ?at the front with!Desult2Wanted A SbU:T

    L.-t De-tru+t.,n

    F.r-t' 6e -7,6 7,6 t, re),8e t7e 0.r-t ele)ent 0r,) a l.-t;

    S:UT A Sf,r,e,dT will result in

    :Af FF $he first element of the list is known as the E'6 of the list. ASr,e,dT

    Re+ur-.,n u-.ng LIST

    print2a2list(ST).print2a2list(SU$T)!< write(), print2a2list($).

    ists, for now, can be regarded as special Pr,l,gstructures that can be used to represent an orderedseJuence of Pr,l,gterms. "or e&ample, here are some legal lists!

    Sice2cream, coffee, chocolateT FF a list with three elements (all atoms)

    Sa, b, c, c, d, eT FF a list with si& elements (all atoms)

    S T FF a list with no elements in it (it is an atom)

    Sdog(fido), cat(rufus), goldfish(immy)T FF a list with three elements (all %rolog terms)

    Shappy(fred),Sice2cream,chocolateT,S3,S@T,5TT FF a list with three elements?

    $he last e&ample is a little difficult to decipher! the first element is happy(fred), the second isSice2cream,chocolateT, a list, and the third is S3,S@T,5T, another list.

    Me)?er

    )e)?er/"'"JR2; )e)?er/"'YJ

    R2 )e)?er/"'R2;

    8ne can read the clauses the following way, respectiely! :

    is a member of a list whose first element is :.

    : is a member of a list whose tail is D if : is a member of D.

    $his program can be used in numerous ways. 8ne can testmembership!*< member(@,S3,@,5T).es

  • 7/26/2019 Prolog_LabSheet

    16/34

    E"AMPLES

    8ne can generate members of alist! *< member(:,S3,@,5T).: A 3 ;: A @ ;

    : A5 ; oere is a deriation tree showing how this last goal generated all of the answers.

    Each left branch corresponds to a match (unification) against the first clause for HmemberH and eachright branch corresponds to a match against the second clause. $he sub goal Hmember(:,ST)H on thelowest right branch will not match the head of any HmemberH clause. In particular HSTH will not unify witha pattern of the form HS:UDTH because the latter represents a list with at least one element.We will find many other uses for HmemberH. $his e&ample Juery.

    )e)?er/3'Y' 1'a'%')'3'K''8'3'*2;

    A R ; Ap ; o

    #uggests a use where one intends to search in order to find elements paired with a specified element.ere is another, finding elements of a list which satisfy some constraint!

    )e)?er/"'%3'@''1%'%%%'1''2' Y .- ""' Y 1::;

    : A N A O3 ;

    : A B A 5B ;o

    $he definition for HmemberH is usuallywritten )e)?er/"'"J2;)e)?er/"'JR2 )e)?er/"'R2;

    where H2H (underscore) designates a VdonHt

  • 7/26/2019 Prolog_LabSheet

    17/34

    W r. t.n g l. - t

    w r i t el is t (S T ) .

    w r i t el is t (S U$ T )! < w r i t e( ), nl , w ri t el is t ( $ ) .

    W r. t.n g re8er- e l. - t

    ethod 3 !re2list(S T) .

    re2list (S U$T )!

  • 7/26/2019 Prolog_LabSheet

    18/34

    !ause(disease1, Hsymptom1J).!ause(disease2, Hsymptom2J).

    !ause(disease$, Hsymptom$J).!ause(disease%, Hsymptom1, symptom2J).!ause(disease&, Hsymptom1, symptom$J).!ause(disease', Hsymptom2, symptomJ).

    !ause(disease, Hsymptom1, symptom2, symptom$J).

    diagnose(erson! "isease#:-su4ers_from(Person, -ymptoms),!ause(*isease, -ymptoms).

    -u00er-0r,)/Per-,n' S5)*t,)-2

    write(M %atient name * M), read(%atient),

    write(M Gie list of symptoms M), read(#ymptoms).7.9,+t,r

    diagnose(%erson, 6isease),

    write(%erson),nl,write(6isease),nl.

    LAB#1:

    TO STUDY SENTENCE PARSING

    Senten+e *ar-.ng ar+7.te+ture

    #entence

  • 7/26/2019 Prolog_LabSheet

    19/34

    oun %hrase Xerb %hrase

    'rticle oun Xerb oun %hrase

    'rticle oun

    $he man likes the horse

    A PROLOG APPLICATION / Rule ?a-e2

    parse#entence(:) !< sentence(:,ST).

    sentence(#tart, End) !< nounphrase(#tart, Dest),erbphrase(Dest, End).

    nounphrase(SounUEndT,End) !< noun(oun).

    nounphrase(S'rticle, ounUEndT,End) ! B 9 .

    E ( a )*l e1 %

    * < $ i m e is 5 mi n ut e s .

    $ i m e A 3O 9yes

    STRINGIING AND TO!EN PASTING

    T,>en

    $oken is the smallest unit in a program which can0t be broken up more into its components by theprogram.

    includeZstdio.h

    Y define

    X'D(i,) (i)

    define paster(n) printf(VtokenV n VA [dV, tokenn)

    oid main(oid)

    \int R3A@;

    int a AX'D(R,3);

    int tokeniA5;

    paster(i);

    ]

  • 7/26/2019 Prolog_LabSheet

    27/34

    ( ; ; un. 8 2 +r,-- +,n8ert- 0,r ter) an9 l.-t ;

    *< % A.. Sa,b,cT.

  • 7/26/2019 Prolog_LabSheet

    28/34