27701472 introduction to flex

Upload: smilevinoth

Post on 29-May-2018

214 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/9/2019 27701472 Introduction to Flex

    1/97

    Introduction to FlexIntroduction to Flex

    From: Sec.1 , Flex Tutorial, by Clive Spenser,

    LPA.

  • 8/9/2019 27701472 Introduction to Flex

    2/97

    Flex Tutorial 2

    1.1 What Is Flex1.1 What Is Flex

    Flex is a language specially designed for the

    development and delivery of Expert Systems.

    It is implemented in Prolog but looks much more like

    standard English than a programming language.

    This is a feature of its Knowledge Specification

    Language (KSL).

    Flex is very functional and can carry out most of theprocedures needed to build knowledge-based

    systems.

  • 8/9/2019 27701472 Introduction to Flex

    3/97

    Flex Tutorial 3

    1.1.1 What Are Flex Programs1.1.1 What Are Flex Programs

    A Flex program is a collection of KSL statements.

    Programs are stored in standard ASCII text files, and

    can be edited using either the development

    environments internal editor or any external text

    editor or word-processor.

  • 8/9/2019 27701472 Introduction to Flex

    4/97

    Flex Tutorial 4

    1.1.2 How Does Flex Relate to Prolog1.1.2 How Does Flex Relate to Prolog

    Flex is implemented in Prolog; it extends the

    traditional Prolog environment, and yet still gives

    access to the underlying Prolog.

    You do not need to know Prolog to use Flex, though

    being familiar with Prolog syntax and basic Prolog

    commands is useful.

    For instance, by using the listing command, you can

    actually see the internal (Prolog) representation of

    your Flex (KSL) code.

  • 8/9/2019 27701472 Introduction to Flex

    5/97

    Flex Tutorial 5

    1.1.3 Constructs in Flex1.1.3 Constructs in Flex

    Flex contains many constructs ideal for building

    knowledge-based systems (frames, instances, rules,

    relations, groups, questions, answers, demons,

    actions, functions).

    You may wish to use some or all of these in building

    your Knowledge-Based Systems (KBS).

    You do not have to learn to use all of them at once!

  • 8/9/2019 27701472 Introduction to Flex

    6/97

    Flex Tutorial 6

    1.1.4 How Extendable Is Flex?1.1.4 How Extendable Is Flex?

    Flex can recognize and compile both Flex (.KSL files)

    and Prolog (.PL files).

    If you find you cannot do what you want in Flex, then

    it can probably be accomplished in Prolog.

    If it cannot be done in Prolog, then you can always

    use the C interface and do it in C, or Java or some

    other low-level language.

  • 8/9/2019 27701472 Introduction to Flex

    7/97

    Flex Tutorial 7

    1.1.5 Naming Conventions in Flex1.1.5 Naming Conventions in Flex

    Often Flex lets you re-use the same name to define

    different constructs; e.g. you may have a question

    named drink, and a group of the same name.

    You do not have to make use of this facility and may

    wish to employ a more explicit naming convention, for

    instance, where the question is named

    drink_question and the group named

    drink_group.

  • 8/9/2019 27701472 Introduction to Flex

    8/97

    Flex Tutorial 8

    1.2 Basic Flex Constructs1.2 Basic Flex Constructs

    1.2.1 KSL Sentences1.2.1 KSL Sentences The basic unit of compilation in Flex is the sentence.

    Sentences are made up of one or more KSL

    statements containing conditions and/or directives,

    and are terminated with a full stop.

  • 8/9/2019 27701472 Introduction to Flex

    9/97

    Flex Tutorial 9

    1.2.2 Conditions and Directives1.2.2 Conditions and Directives

    Conditionstest whether or not something iscurrently true.

    Directiveschange the current state of an object tosome new state.

    The context will determine which of these Flex will

    expect.

  • 8/9/2019 27701472 Introduction to Flex

    10/97

    Flex Tutorial 10

    1.3 Installing and Starting Flex1.3 Installing and Starting Flex

    Load Flex with a double click on the Flex shortcut.

    Flex loads in a few seconds.

    If you have used Prolog before, you will recognize the

    Console window but should notice an extra menu

    named Flex.

    The File and Edit menus are very similar to other

    Windows applications. Open the menus to confirm

    this.

  • 8/9/2019 27701472 Introduction to Flex

    11/97

    Flex Tutorial 11

    1.4 Important Tips1.4 Important Tips

    1.4.1 The Console window1.4.1 The Console window The first window you see is the Console window with

    the standard Prolog ?- prompt.

    This window is used for communication between you

    and the system.

  • 8/9/2019 27701472 Introduction to Flex

    12/97

    Flex Tutorial 12

    1.4.2 Create a New File1.4.2 Create a New File

    File New"Untitled" Save As

  • 8/9/2019 27701472 Introduction to Flex

    13/97

    Flex Tutorial 13

    1.4.3 The Run Menu1.4.3 The Run Menu

    The Run menu is used to compile and run your

    code.

  • 8/9/2019 27701472 Introduction to Flex

    14/97

    Flex Tutorial 14

    1.4.4 Analysing Syntax Errors1.4.4 Analysing Syntax Errors

    Pull down the Flex menu and make sure the Analyse

    Syntax Errors item is enabled (ticked) before you

    enter code.

    If the system detects any mistakes during

    compilation, it will make suggestions as to what is

    wrong.

    If Analyse Syntax Errors is not ticked, you will just

    get a Cannot Parse Sentence... error without anyexplanations as to why.

  • 8/9/2019 27701472 Introduction to Flex

    15/97

    Flex Tutorial 15

    1.4.5 How Are Flex Programs Compiled?1.4.5 How Are Flex Programs Compiled?

    The KSL compiler translates Flex programs into an

    internal Prolog-based representation which is

    interpreted by the Flex run-time system.

    In the case of a KSL syntax error, the parser attempts

    to identify what caused the error and what alternative

    words would have been acceptable.

  • 8/9/2019 27701472 Introduction to Flex

    16/97

    Flex Tutorial 16

    1.4.6 How Are Flex Programs Executed?1.4.6 How Are Flex Programs Executed?

    There is usually a top-level actionassociated with aFlex program to start it off.

  • 8/9/2019 27701472 Introduction to Flex

    17/97

    Flex Tutorial 17

    1.4.7 Restarting Flex?1.4.7 Restarting Flex?

    Closing a Flex file does not automatically remove

    associated definitions.

    You can clear memory by typing the initialise

    command into the console window at the ?-prompt.

    Alternatively, you can use the Initialise Workspace

    item on the Flex menu.

  • 8/9/2019 27701472 Introduction to Flex

    18/97

    Flex Tutorial 18

    1.4.8 How Do I Stop Flex (or Prolog) Looping1.4.8 How Do I Stop Flex (or Prolog) Looping

    CONTROL + BREAK

  • 8/9/2019 27701472 Introduction to Flex

    19/97

    Flex Tutorial 19

    1.4.9 Use of Semicolons1.4.9 Use of Semicolons

    Often, semicolons are used as delimiters, for

    instance within actions, frames etc.

  • 8/9/2019 27701472 Introduction to Flex

    20/97

  • 8/9/2019 27701472 Introduction to Flex

    21/97

    Flex Tutorial 21

    1.4.11 Use of the $ Character1.4.11 Use of the $ Character

    One important difference between the Flex andProlog execution models is that Flex will attempt toprove goals rather than directly execute them.

    This involves a layer of interpretation such that Flexcan de-reference (evaluate) any arguments locatedwithin the scope of the goal statement, unless toldnot to by the $ symbol.

    Flex de-references its arguments before a call ismade. The $ character can be used to inhibit this andforce the use of conventional Prolog pattern matching(called unification).

  • 8/9/2019 27701472 Introduction to Flex

    22/97

    Flex Tutorial 22

    1.4.12 Debugging in Flex1.4.12 Debugging in Flex

    Because the trace facility in Flex works at the Prolog

    level, you may find it more helpful to insert write

    statements within your flex code at the appropriate

    points, followed by a new-line.

  • 8/9/2019 27701472 Introduction to Flex

    23/97

    Starting ProgrammingStarting Programming

    From: Sec.2, Flex Tutorial, by Clive Spenser,

    LPA.

  • 8/9/2019 27701472 Introduction to Flex

    24/97

    Flex Tutorial 24

    2.1 First Program2.1 First Program

    We will start by defining a question and anaction. The outline structure for these are:

    question question_name

    prompt text for question ;

    input datatype [ ;

    because explanation ] .

    action action_name ;

    do directive(s) .An example

  • 8/9/2019 27701472 Introduction to Flex

    25/97

    Flex Tutorial 25

    question your_namePlease enter your name ;

    input name .action hullo ;

    do ask your_nameandwrite( 'hi there ' )

    andwrite( your_name )andnl .

    2.1 First Program2.1 First Program

  • 8/9/2019 27701472 Introduction to Flex

    26/97

    Flex Tutorial 26

    2.2 Questions and Answers2.2 Questions and Answers

    Flex has a built-in question and answer sub-system.

    You can also generate basic questions using reservedwords such as choose from, input etc.

    Alternatively you can build more sophisticated dialogsby supplying your own code to display them.

    Asking a question generates a dialog box which, in theexample above, awaits keyboard input.

    When you respond, the reply is stored in a variable

    which has the same name as the question, in this caseyour_name.

    You can then refer to your_name to access whateverwas entered.

  • 8/9/2019 27701472 Introduction to Flex

    27/97

    Flex Tutorial 27

    2.3 Compiling and Running Queries2.3 Compiling and Running Queries

    Made sure you do have a .KSL extension.

    Use the Compile item on the Run menu to compileyour code.

    In the Console window, type hullo. at the ?- promptand press .

    You can try clicking on the Explain... button to seewhat happens.

  • 8/9/2019 27701472 Introduction to Flex

    28/97

  • 8/9/2019 27701472 Introduction to Flex

    29/97

    Frames and InstancesFrames and Instances

    From: Sec.3, Flex Tutorial, by Clive Spenser,

    LPA.

  • 8/9/2019 27701472 Introduction to Flex

    30/97

    Flex Tutorial30

    3.1 Frames and Instances3.1 Frames and Instances

    In Flex, you store knowledge about objects using frame andinstance.

    Frames define classes of objects and instances of framesdescribe individuals within those classes.

    These are organized into a frame hierarchy with informationinherited by either explicit or implicit means.

    The outline structure of a frame is:

    frame frame_name ;

    [default Attribute_Name is Value ]

    [and default Attribute_Name1 is Value1 ] ;

    [inherit Attribute_Name2 fromFrame ] .

  • 8/9/2019 27701472 Introduction to Flex

    31/97

    Flex Tutorial31

    3.1 Frames and Instances3.1 Frames and Instances

    The following code defines a general class ofstudent in a frame.

    frame student ;

    default nationality is american and

    default nature is studious and

    default discipline is computing and

    default residence is texas and

    default major is undecided.

    instance instance_name ;[ Attribute_Name is Value ][ andAttribute_Name1 is Value1 ] .

  • 8/9/2019 27701472 Introduction to Flex

    32/97

    Flex Tutorial32

    instance maria is a studentnature is cheerful andnationality is spanish anddiscipline

    isengineering

    andstatus is sophomore.

    instance anton is a student ;nature is frivolous andnationality is french and

    discipline is mathematics andstatus is freshman andinterests are {tennis,computing,maria} andresidence is paris.

    3.1 Frames and Instances3.1 Frames and Instances

  • 8/9/2019 27701472 Introduction to Flex

    33/97

    Flex Tutorial33

    3.1 Frames and Instances3.1 Frames and Instances

    The textual ordering of the attribute-value pairs isirrelevant.

    The order in which frames and instances are written

    affects the order in which they are accessed. Flex allows you to create instances with the same name

    but belonging to different frames, however, the lastcreated instance will take preference.

    The value of an attribute can be obtained by either ofthe following statements:

    maria`s nationality

    the nationality of maria

  • 8/9/2019 27701472 Introduction to Flex

    34/97

  • 8/9/2019 27701472 Introduction to Flex

    35/97

    Flex Tutorial35

    3.2 Attribute Values3.2 Attribute Values

    You can think of frames and instances as datastructures with a name, three columns and anunspecified number of rows.

    Instances inherit their slot values from theirparent frames unless the values are over-ridden with local (current) definitions.

    Frame/instance slot values, both default and

    current, can be pre-defined in KSL files and/ordynamically created and updated at run-time.

  • 8/9/2019 27701472 Introduction to Flex

    36/97

    Flex Tutorial36

  • 8/9/2019 27701472 Introduction to Flex

    37/97

    More on ActionsMore on Actions

    From: Sec.4, Flex Tutorial, by Clive Spenser,

    LPA.

  • 8/9/2019 27701472 Introduction to Flex

    38/97

    Flex Tutorial38

    4.1 Using the Student Information4.1 Using the Student Information

    BaseBase

    Test a question by, say,?- ask( new_status ).

    question the_student please choose a student ; choose fromanton, maria, john, mary, tom.

    question new_status please select the new status ; choose fromfreshman, sophomore, junior, senior.

    choose some of

  • 8/9/2019 27701472 Introduction to Flex

    39/97

    Flex Tutorial39

    4.2 Scheme for changing a students status4.2 Scheme for changing a students status

    and checking both the old and the new valueand checking both the old and the new value

    1. Use the student frame and the five instancesyou have prepared

    2. Choose a students name using the_student

    question.3. Show the current status with echo or write

    (just to check)

    4. Query for the new status, using the questionnew_status

    5. Use becomes to reset the_students statusattribute

    6. echo or write the new status to screen.

  • 8/9/2019 27701472 Introduction to Flex

    40/97

    Flex Tutorial40

    4.2 Scheme for changing a students status4.2 Scheme for changing a students status

    and checking both the old and the new valueand checking both the old and the new value

    action change_status ;do ask the_studentand echo( ' the status of', the_student,

    ' was ', the_student`s status ).

    and ask new_statusandthe_student`sstatusbecomes new_statusand echo( ' the status of', the_student,

    ' is now', the_student`s status ).

    action change_status ;

    do ask the_student and check that S is the_student

    and echo(' the status of', S, ' was', S`s status ) and ask new_status andS`s statusbecomes new_status

    and echo( ' the status of', S, ' is now', S`s status ).

  • 8/9/2019 27701472 Introduction to Flex

    41/97

    Flex Tutorial41

    4.3 A special frame called global4.3 A special frame called global

    You sometimes need to store values to be usedanywhere in the program.

    These can be put into a special frame called

    global.

    This is what the built-in question and answermechanism uses.

    frame global;default current_year is 1996 anddefault college_name is 'Texas College'.

  • 8/9/2019 27701472 Introduction to Flex

    42/97

    Flex Tutorial42

    4.4 Some aids to formatting4.4 Some aids to formatting

    Use tab(N)to move text across the screen.

    action action_name;

    do write( 'something' )andtab( 10 ) % tab 10 spacesandwrite( 'Something else' ) .

    The forloop is very much like that found inany other programming language.

    action half_screen;do for N from0 to 10do nlend for .

  • 8/9/2019 27701472 Introduction to Flex

    43/97

    Flex Tutorial43

    4.4 Some aids to formatting4.4 Some aids to formatting

    Modify the hullo program of sections 0 touse half_screen twice:

    action hullo ;do half_screenandask your_nameand echo( 'Hi ', your_name )and ask your_age

    andwrite( 'I think ' )andwrite( your_age )andwrite( 'is cool!' )andhalf_screen .

  • 8/9/2019 27701472 Introduction to Flex

    44/97

    Flex Tutorial44

    4.4 Some aids to formatting4.4 Some aids to formatting

    action student_status ;do for every Student is some instance of student% Student is a local variable

    % it starts with uppercase.do write( Student )andwrite( ' record is ' )andnlandtab( 5 )andwrite( 'Nationality is ' )andwrite( Student`s nationality )and% etc.end for

  • 8/9/2019 27701472 Introduction to Flex

    45/97

    Flex Tutorial45

    4.4 Some aids to formatting4.4 Some aids to formatting

    action do_something ;do check that X is a studentand check that the nationality of X is Yandwrite( X-Y ) .

    action do_something_else ;do check that [ X is a student

    andnationality

    ofXis

    Y ]

    andwrite( X-Y ) .

    OR

  • 8/9/2019 27701472 Introduction to Flex

    46/97

    Some Technical NotesSome Technical Notes

    From: Sec.5, Flex Tutorial, by Clive Spenser,

    LPA.

  • 8/9/2019 27701472 Introduction to Flex

    47/97

    Flex Tutorial 47

    5 Some technical notes5 Some technical notes

    In order to be able to talk intelligently about aspects ofprogramming in a language (whether in Flex or in anyother language) we all need to understand and be ableto name the basic units of the language.

    The basic unit in Flex is a token.

    Tokens are treated as single items by the compiler.

    Flex uses various types of Prolog token: punctuation,number, atom, string, byte list and variable, and built

    on top of these Prolog tokens are the concepts of a KSLname and a KSL value.

  • 8/9/2019 27701472 Introduction to Flex

    48/97

    Flex Tutorial 48

    5.1 Comments and punctuation5.1 Comments and punctuation

    /* */a block comment.

    %a single line comment

    ( ) [ ] { } | ! ; ,

    are all treated asseparate items and each one is a token.

  • 8/9/2019 27701472 Introduction to Flex

    49/97

    Flex Tutorial 49

    5.2 Numbers5.2 Numbers

    Numbers are either integers or floating-pointnumbers.

    211327 -32768 0 2.34 10.3e99 -0.81

  • 8/9/2019 27701472 Introduction to Flex

    50/97

    Flex Tutorial 50

    5.3 Atoms5.3 Atoms

    Atoms are of three types:alphanumeric, symbolicand quoted. alphanumeric

    apple aPPLE h45j apple_cartorangesAndApples

    symbolic

    a contiguous sequence of symbols such as

    *, >, or #. quoted

    'Apple' '123' 'The green man' '^h''ht'

  • 8/9/2019 27701472 Introduction to Flex

    51/97

    Flex Tutorial 51

    5.4 Byte Lists5.4 Byte Lists

    Characters enclosed in double quotes aretreated as lists of ASCII characters.

    A boy is shorthand for [65,32,98,111,121].

    For the technically minded: LPA is a 32-bitsystem. Each character occupies 4 bytes butonly one of them is used - this is wasteful. Inaddition, there is a 4 byte pointer to eachcharacter - add the type tags and it turns outthat each character uses 10 bytes ofmemory!!

  • 8/9/2019 27701472 Introduction to Flex

    52/97

    Flex Tutorial 52

    5.5 Strings5.5 Strings

    LPA offers a special dedicated string data typefor text items denoted by the use ofbackwards quotes.

    The maximum length of these `strings` is 64K(much bigger than regular atoms).

    For the technically minded: Thismethod of string storage uses

    approximately 1.3 bytes per character.This is quite efficient. Maximum length65535 bytes - compare atoms.

  • 8/9/2019 27701472 Introduction to Flex

    53/97

    Flex Tutorial 53

    5.6 Variables5.6 Variables

    A (logical) variable is an uppercase letter (A-Z) or an underscore (_), followed by asequence of zero or more alphabetic

    characters (a-z, A-Z or _) or digits (0-9).MrSpock Apple APPLE _23 X.

    The underscore on its own _ is the don`tcare variable. Its contents are not stored.

  • 8/9/2019 27701472 Introduction to Flex

    54/97

    Flex Tutorial 54

    5.7 Names5.7 Names

    A name is any quotedatom, or any atomwhich is not a reserved word (i.e. an atomwhich does not appear in the glossary of the

    KSL).brick brick32 'The' 'the brick'

  • 8/9/2019 27701472 Introduction to Flex

    55/97

    Flex Tutorial 55

    5.8 Values5.8 Values

    A value is any number, any string or anyname.

  • 8/9/2019 27701472 Introduction to Flex

    56/97

    Forward-chaining Production RulesForward-chaining Production Rules

    From: Sec.6, Flex Tutorial, by Clive Spenser,

    LPA.

  • 8/9/2019 27701472 Introduction to Flex

    57/97

    Flex Tutorial 57

    6.1 Rules6.1 Rules

    Forward-chaining (production) rules are usedby the (meta-level) forward-chaining engine inFlex.

    rule rule_name

    if condition(s)

    then directive(s) ;

    [because explanation ] ;[ score score_expression ] .

  • 8/9/2019 27701472 Introduction to Flex

    58/97

    Flex Tutorial 58

    rule check_residence1if the_student`s residence is not included in

    {london,texas,kensington}

    andthe_student`s status is included in{freshman,sophomore}then echo( 'it will be necessary to book accommodation

    at texas for ', the_student ).

    rule check_residence2if the_student`s residence is included in{london,texas,kensington}then echo( 'it will not be necessary to book

    accommodation at texas for ', the_student ).

    6.1 Rules6.1 Rules

  • 8/9/2019 27701472 Introduction to Flex

    59/97

    Flex Tutorial 59

    6.2 Rulesets6.2 Rulesets

    You will appreciate that in a large application there maybe many hundreds of rules.

    It is convenient to group sets of rules which belongtogether and may be relevant at one particular stage ofprocessing.

    Such a group is called a ruleset.

    However, if you dont want to have discrete groups, youcan inform Flex of this by using the general definition:

    ruleset set1

    contains all rules.

    frame student; % the name of the frame

  • 8/9/2019 27701472 Introduction to Flex

    60/97

    Flex Tutorial 60

    default nationality is american and % frame attributes always Odefault nature is studious and % O have default keyword.default discipline is computing anddefault residence is texas anddefault major is undecided.

    instance maria is a student; % parent frame is studentnature is cheerful andnationality is spanish anddiscipline is engineering andstatus is sophomore andresidence is madrid.

    instance anton is a student;nature is frivolous andnationality is french anddiscipline is mathematics andstatus is freshman andinterests are {tennis,computing,maria} andresidence is paris.

    instance margaret is a student;nature is sporty andnationality is finnish anddiscipline is art andstatus is freshman andinterests are {tennis,computing,anton} andresidence is texas.

    Part 1

    rule check_residence1if S is an instance of student and not checked( S )

  • 8/9/2019 27701472 Introduction to Flex

    61/97

    Flex Tutorial 61

    if S is an instance of student and not checked( S )and S`s residence is not included in {london,texas,kensington}and S`s status is included in {freshman,sophomore}then echo( 'it will be necessary to book accommodation at texas for', S )and S`s residence becomes texasand echo( 'The residence for ', S, ' is now', S`s residence, 'by rule1' )

    and remember that checked( S ).rule check_residence2

    if S is an instance of student and not checked( S )and S`s residence is not included in {london,texas,kensington}and S`s status is not included in {freshman,sophomore}then echo( 'it will be necessary to book accommodation at kensington for ', S )and S`s residence becomes kensington

    and echo('The residence for ', S, ' is now ', S`s residence, 'by rule2' )and remember that checked( S ).rule check_residence3

    if S is an instance of student and not checked( S )and S`s residence is included in {london,texas,kensington}and S`s status is included in {freshman,sophomore,junior,senior}then echo( 'it will not be necessary to book accommodation attexas for ', S, 'by rule3' )

    and remember that checked( S ).ruleset set1

    contains all rules;select rule using first come first served.

    action residence;do restart % this clears any remembered factsand echo( starting, check )and invoke ruleset set1and echo( finished, check ).

    Part 2

  • 8/9/2019 27701472 Introduction to Flex

    62/97

    Flex Tutorial 62

    6.2 Rulesets6.2 Rulesets

    Flex provides three methods of determiningthe order in which to select rules: first come first served, in which it picks the

    rules in the order in which they appear in the file; conflict resolution, where the best rule is picked

    according to a score; and

    conflict resolution with thresholdwhich picksthe first rule whose score is above a user supplied

    threshold. This score is defined using the scoreclause in rules.

  • 8/9/2019 27701472 Introduction to Flex

    63/97

  • 8/9/2019 27701472 Introduction to Flex

    64/97

    Flex Tutorial 64

    6.3 Facts and exceptions6.3 Facts and exceptions

    Everything the expert system knows about the currentstate of its world is contained in frames and instancesand in facts and exceptions.

    Flex maintains two databases: one of facts, which are

    true, and one of exceptions, which are not true. These are entered during run-time and exist only for

    the duration of the session.

    They are entered with the keywords remember thatand removed with the keywords forget that.

    The facts and exceptions will either be obtained asanswers to questions or as consequences of applyingproduction rules - where the consequences will containa line such as remember that and/or forget that...

  • 8/9/2019 27701472 Introduction to Flex

    65/97

    Flex Tutorial 65

    6.4 Groups6.4 Groups

    Groups are name collections like sets.

    Think of them as type declarations but with abuilt in ordering.

    Groups are often used to collect items to feedinto a question.

    group wall_colours

    magnolia, coffee, apple_white, barley, buttermilk .

    question wall_colour

    Please choose a colour for your room ;

    choose fromwall_colours .

  • 8/9/2019 27701472 Introduction to Flex

    66/97

    Flex Tutorial 66

    6.5 Relations6.5 Relations

    In Flex, relations are used to representbackward-chaining rules and have the form:

    relation relation_name(arg1,arg2,..., argN)

    if condition(s) .

  • 8/9/2019 27701472 Introduction to Flex

    67/97

    Flex Tutorial 67

    6.5 Relations6.5 Relations

    Relations are like actions. However, whereasactions can only have one definition, relationscan have multiple (alternative) definitions.

    Relations can be called directly from within anaction (like the system predicates echo andwrite).

    Relations can be used in the if or then part of

    (forward-chaining) rules. Relations can call other relations.

    frame student

  • 8/9/2019 27701472 Introduction to Flex

    68/97

    Flex Tutorial 68

    frame student.

    instance maria is a student ;nature is cheerful and

    nationality is spanish andstatus is freshman andresidence is madrid.

    relation check_residence( S )if S`s status is included in {freshman,junior}

    and S`s residence is not included in {texas,london}and echo( 'we need to book accommodation for', S, 'at texas' ).

    /* this definition is used when the first one fails */relation check_residence( S )if echo( S, ' does not need to have accommodation booked' ).

    action test;do for every S is an instance of studentdo check_residence( S ) and write( S ) and nlend for.

  • 8/9/2019 27701472 Introduction to Flex

    69/97

    Flex Tutorial 69

    relation check_residence1( S, Residence )if S`s status is included in {freshman,junior}

    and S`s residence is not includedin {texas,london}and check that Residence is S`s residenceandecho( 'we need to book accommodation for', S, 'at texas' ).

    /* this definition is used when the first one fails */.

    relation check_residence1( S, Residence )if echo( S, ' does not need to have accommodation booked' )and check that Residence is S`s residence.

    action test1 ;do for every S is an instance of student

    docheck_residence1( S, Residence )

    andwrite( S - Residence ) andnlend for .

  • 8/9/2019 27701472 Introduction to Flex

    70/97

    Flex Tutorial 70

    6.6 Templates6.6 Templates

    Flex provides a template facility to make KSL morereadable.

    Templates are replaced at compile time by textsubstitution. Carets (^) are used to indicate where anyvariables may be.

    The outline structure for a template is:

    template label_to_replace

    positive_template ;

    negative_template .

  • 8/9/2019 27701472 Introduction to Flex

    71/97

  • 8/9/2019 27701472 Introduction to Flex

    72/97

  • 8/9/2019 27701472 Introduction to Flex

    73/97

    ProjectsProjects

    From: Sec.7, Flex Tutorial, by Clive Spenser,

    LPA.

  • 8/9/2019 27701472 Introduction to Flex

    74/97

  • 8/9/2019 27701472 Introduction to Flex

    75/97

    Data Driven ProgrammingData Driven Programming

    From: Sec.8, Flex Tutorial, by Clive Spenser,

    LPA.

  • 8/9/2019 27701472 Introduction to Flex

    76/97

    Flex Tutorial 76

    8. Data Driven Programming8. Data Driven Programming

    There are four types of procedure which takeplace automatically when data in frames orinstances is added or changed. These are:

    launches, constraints,

    demons and

    watchdogs.

    Sometimes this technique is called proceduralattachment and is often found in objectoriented systems.

  • 8/9/2019 27701472 Introduction to Flex

    77/97

    Flex Tutorial 77

    8.1 Launches8.1 Launches

    A launch is a procedure which can be attached to aframe and is automatically invoked whenever a newinstance of that frame is created.

    Its primary use is in setting up the initial characteristicsof frame instances.

    The directives associated with a launch are executedimmediately afterthe instance is created.

    A launch can be tailored such that it fires only undercertain circumstances.

    The outline structure for a launch is:launch launch_name

    when Instance is a new [ instance of ] Frame

    andcondition(s)

    then directive(s) .

  • 8/9/2019 27701472 Introduction to Flex

    78/97

    Flex Tutorial 78

    8.1 Launches8.1 Launches

    launch new_studentwhen S is a new studentandS is not exit

    then ask s_nationality.

  • 8/9/2019 27701472 Introduction to Flex

    79/97

    Flex Tutorial 79

    8.2 Constraints8.2 Constraints

    A constraint is a validity check which can be attached toan attribute of a frame.

    It is automatically invoked whenever the value for thatslot changes.

    The checks associated with a constraint are executedimmediately before the value of the slot is to bechanged, and the value only changes if the checkssucceed.

    If any check fails then the slot is notupdated, and theupdate itself will fail.

    Note that a demon may be used to perform checks aftera slot value has changed.

  • 8/9/2019 27701472 Introduction to Flex

    80/97

    Flex Tutorial 80

    8.2 Constraints8.2 Constraints

    The outline structure of a constraint

    constraint constraint_namewhen Attribute changes[ fromExpression1 to Expression2 ][ andcondition1(s) ]then check that condition2(s)[ otherwise directive(s) ] .

  • 8/9/2019 27701472 Introduction to Flex

    81/97

    Flex Tutorial 81

    8.3 Demons8.3 Demons

    A demon is a procedure which can be attached toan attribute of a frame.

    It is automatically invoked whenever the valuefor that slot changes.

    The directives associated with a demon areexecuted immediately afterthe slot valuechanges.

    A demon can be tailored such that it fires only for

    given values and/or only under certaincircumstances.

    Note that a constraint may be used to performchecks before a slot value is changed.

  • 8/9/2019 27701472 Introduction to Flex

    82/97

    Flex Tutorial 82

    8.3 Demons8.3 Demons

    The outline structure

    demon demon_namewhen Attribute changes[ fromExpression1 to Expression2 ][ andcondition1(s) ]

    then directive(s) .

  • 8/9/2019 27701472 Introduction to Flex

    83/97

    Flex Tutorial 83

    8.4 Watchdogs8.4 Watchdogs

    A watchdog checks the access rights to anattribute of a frame.

    It is automatically invoked whenever there is a

    request for the currentvalue (not the defaultvalue) of that slot.

    The checks associated with a watchdog areexecuted immediately before the value is

    accessed. If the check fails then the access call also fails.

  • 8/9/2019 27701472 Introduction to Flex

    84/97

    Flex Tutorial 84

    8.4 Watchdogs8.4 Watchdogs

    The outline structure of a watchdog :

    watchdog watchdog_name

    when Attribute is requestedandcondition1(s)then check that condition2(s)otherwise directive(s) .

    This is a natural for password protection.

    when the status of student is requestedthen do password....

  • 8/9/2019 27701472 Introduction to Flex

    85/97

    Directives and ConditionsDirectives and Conditions

    From: Sec.9, Flex Tutorial, by Clive Spenser,

    LPA.

  • 8/9/2019 27701472 Introduction to Flex

    86/97

    Flex Tutorial 86

    9.1 Directives9.1 Directives

    Directives are used to change the current stateto some new state, where a state consists ofthe global variables, frames, instances, facts

    and exceptions.

  • 8/9/2019 27701472 Introduction to Flex

    87/97

    Flex Tutorial 87

    9.1.1 Assignments9.1.1 Assignments

    The changing of global variables, frames andinstances is known as assignment.

    There are two kinds of assignment, direct

    assignments and assignments which happenas the result of creation of a new frame orinstance.

  • 8/9/2019 27701472 Introduction to Flex

    88/97

    Flex Tutorial 88

    9.1.1.1 Direct Assignments9.1.1.1 Direct Assignments

    A direct assignmentconsists of a variant onthe left hand side and an expression on theright hand side of an assignment operator.

    Variant := Expression

    Variantbecome ExpressionVariantbecomes Expression

    Examples

    methane_level := highthe kettle`s temperaturebecomes 45the cinema`s filmsbecome

    { 'Gone With the Wind', 'Star Wars' }

  • 8/9/2019 27701472 Introduction to Flex

    89/97

    Flex Tutorial 89

    9.1.1.2 New instances9.1.1.2 New instances

    Directives can dynamically create newinstances of frames with local attributes.

    All other attributes of the parent frame will

    automatically be inherited by the instance.

    Instance is a new FrameInstance is another Frame

    'Tiddles' is another cat whose owner is alexanderplant33 is a new plant whose size is medium

  • 8/9/2019 27701472 Introduction to Flex

    90/97

    Flex Tutorial 90

    9.1.2 Database Maintenance9.1.2 Database Maintenance

    The addition and removal of facts and exceptions isclassed as database maintenance.

    Database maintenance is accomplished by directiveswhich add assertions to, or delete assertions from boththe positive (facts) and the negative (exceptions)

    databases. Facts may be added and removed using the following

    KSL keywords:

    remember remember that forget forget that

    Examples

    remember that pregnant( P )

    remember likes( alexander, harvey )

    remember not raining

    forget danger_level( red )

    forget that not boiling

  • 8/9/2019 27701472 Introduction to Flex

    91/97

    Flex Tutorial 91

    9.2 Conditions9.2 Conditions

    A condition is used to test the current state(for example of global variables, frames orfacts).

    Conditions either test for the existence of avariant or compare the value of twoexpressions; a condition may also be aprocedure call.

  • 8/9/2019 27701472 Introduction to Flex

    92/97

    Flex Tutorial 92

    9.2.1 Equality Comparison9.2.1 Equality Comparison

    isareis equal toExamples

    alpha = beta / 2jugA`s contents are jugA`s capacitythe size of some brick is equal to 4the employee`s name is phil

    not alpha = betanot the pupil`s mark is 70X is an elephantX is a kind of animal whose ears are small

  • 8/9/2019 27701472 Introduction to Flex

    93/97

    Flex Tutorial 93

    9.2.2 Direct Comparison9.2.2 Direct Comparison

    greater than [or equal to][at or] aboveless than [or equal to][at or] below

    alpha > beta / 2the temperature =< the 'freezing point' of waterthe pupil`s mark is not below 50

    the temperature is at or above boiling_pointthe likelihood of frost is less than probablethe food`s calories is less than or equal to 400

  • 8/9/2019 27701472 Introduction to Flex

    94/97

    Flex Tutorial 94

    9.2.3 Relative Comparison9.2.3 Relative Comparison

    its colour is at or above the colour of moneyaccording to { red , blue , white , green }

    group fuzzy_orderingcertain, probable, possible, unlikely, impossible .

    the likelihood of frost is less than probableaccording to fuzzy_ordering

  • 8/9/2019 27701472 Introduction to Flex

    95/97

    Flex Tutorial 95

    9.2.4 Set Membership9.2.4 Set Membership

    include(s)included indo(es) not include.

    Examplesthe staff include { john and mary }a surprise is included in the contents of the box

    the Rodent`s tail does not include bushy

  • 8/9/2019 27701472 Introduction to Flex

    96/97

  • 8/9/2019 27701472 Introduction to Flex

    97/97

    9.4 Context Switching9.4 Context Switching

    If you wish to use a condition where a directiveis expected, then the context can be switchedby inserting the word(s) check[ that ].

    For example, an action requires directives buta relation requires conditions.

    Examples

    relation emp_name( Emp, Name )

    if Name is Emp`s name .action emp_name( Emp, Name ) ;

    do check that Name is Emp`s name .