Вы находитесь на странице: 1из 34

CLIPSProgramming3

ModularDesign,Execution
Control,andRuleEfficiency
SEEM 5750 1
Deftemplate Attributes DeftemplateAttributes
d b f l b h b f d h CLIPSprovidesanumberofslotattributesthatcanbespecifiedwhena
deftemplatesslotsaredefined.
Itispossibletodefinetheallowedtypesandvaluesthatcanbestoredina p yp
slot.
SEEM 5750 2
The Type Attribute TheTypeAttribute
h b d f h d h b l d l Thetypeattributedefinesthedatatypesthatcanbeplacedinaslot.
Thegeneralformatofthetypeattributeis
( t ype <t ype- speci f i cat i on>) ( t ype t ype speci f i cat i on )
where<type-specification>iseither
?VARIABLEor
one or more of the symbols oneormoreofthesymbols
SYMBOL,
STRING,
LEXEME,
INTEGER,
FLOAT,
NUMBER,
INSTANCENAME, INSTANCE NAME,
INSTANCEADDRESS,
INSTANCE,
FACTADDRESS,or
EXTERNAL-ADDRESS EXTERNAL-ADDRESS.
SEEM 5750 3
The Type Attribute TheTypeAttribute
E l Example:
( def t empl at e per son
( mul t i sl ot name ( t ype SYMBOL) )
( sl ot age ( t ype I NTEGER) ) )
Forexample,assigningthesymbolfourtotheageslotratherthanthe p , g g y g
integer4willcauseanerrorasshown:
CLI PS> ( asser t ( per son ( name Fr ed Smi t h)
( age f our ) ) ) ( age f our ) ) )
[CSTRNCHK1]Aliteralslotvaluefoundintheassertcommanddoesnot
matchtheallowedtypesforslotage.
CLIPS> CLIPS>
SEEM 5750 4
The Allowed Value Attributes TheAllowedValueAttributes
l ll f l f ll d l f f CLIPSalsoallowsyoutospecifyalistofallowedvaluesforaspecifictype.
Forexample,ifagenderslotisaddedtothepersondeftemplate,the
allowedsymbolsforthatslotcanberestrictedtomaleandfemale: y f
( def t empl at e per son(
mul t i sl ot name ( t ype SYMBOL) )
( sl ot age ( t ype I NTEGER) ) ( sl ot age ( t ype I NTEGER) )
( sl ot gender ( t ype SYMBOL)
( al l owed- symbol s mal e f emal e) ) )
SEEM 5750 5
The Allowed Value Attributes TheAllowedValueAttributes
Th i ht diff t ll d l tt ib t id d b CLIPS ThereareeightdifferentallowedvalueattributesprovidedbyCLIPS:
allowedsymbols,allowedstrings,allowedLexemes,allowedintegers,allowedfloats,
allowednumbers,allowedinstancenames,andallowedvalues.
For example (allowedsymbols male female) does not restrict the type of the Forexample,(allowedsymbolsmalefemale)doesnotrestrictthetypeofthe
genderslottobeingasymbol.
Itmerelyindicatesthatiftheslotsvalueisasymbol,thenitmustbeoneof
thetwosymbols:eithermaleorfemale. y f
Anystring,integer,orfloatwouldbealegalvalueforthegenderslotifthe
(typeSYMBOL)attributewereremoved
Theallowedvalues attributecanbeusedtocompletelyrestrictthesetofallowed p y
valuesforaslottoaspecifiedlist.
( def t empl at e per son
( mul t i sl ot name ( t ype SYMBOL) )
( sl ot age ( t ype I NTEGER) )
( sl ot gender ( al l owed- val ues mal e f emal e) ) )
SEEM 5750 6
The Range Attribute TheRangeAttribute
h b ll h f f d Therangeattributeallowsthespecificationofminimumandmaximum
numericvalues.
Thegeneralformatoftherangeattributeis g g
(range<lowerlimit><upperlimit>)
where<lowerlimit>and<upperlimit>areeither?VARlABLEoranumeric
value value.
Example:
( def t empl at e per son p p
( mul t i sl ot name ( t ype SYMBOL) )
( sl ot age ( t ype I NTEGER) ( r ange 0 ?VARI ABLE) ) )
SEEM 5750 7
The Cardinality Attribute TheCardinalityAttribute
The cardinality attribute allows the specification of the minimum and Thecardinalityattributeallowsthespecificationoftheminimumand
maximumnumberofvaluesthatcanbestoredinamultislot.
Thegeneralformatofthecardinalityattributeis
( car di nal i t y <l ower l i mi t > <upper l i mi t >) ( car di nal i t y <l ower - l i mi t > <upper - l i mi t >)
where<lowerlimit>and<upperlimit>areeither?VARIABLEorapositive
integer.
Note that type, allowed value, and range attributes are applied to every Notethattype,allowedvalue,andrangeattributesareappliedtoevery
valuecontainedinamultislot.
Example:
( def t empl at e vol l eybal l - t eam ( p y
( sl ot name ( t ype STRI NG) )
( mul t i sl ot pl ayer s ( t ype STRI NG)
( car di nal i t y 6 6) )
( mul t i sl ot al t er nat es ( t ype STRI NG)
( car di nal i t y 0 2) ) )
SEEM 5750 8
The Default Attribute TheDefaultAttribute
It i ft i t t t ti ll h ifi d l t d i Itisoftenconvenienttoautomaticallyhaveaspecifiedvaluestoredina
slotifnovalueisexplicitlystatedinanassertcommand.
Thegeneralformatofthedefaultattributeis
(default<defaultspecification>)
where<defaultspecification>iseither?DERIVE,?NONE,asingleexpression
(forasinglefieldslot),orzeroormoreexpressions(foramultifieldslot).
Ifthedefaultattributeisnotspecifiedforaslot,thenitisassumedtobe
(default?DERIVE).
Forasinglefieldslot,thismeansthatavalueisselectedthatsatisfiesthe
type,range,andallowedvaluesattributesfortheslot.
Thederiveddefaultvalueforamultifieldslotwillbealistofidenticalvalues
thataretheminimumallowedcardinalityfortheslot(zerobydefault).
SEEM 5750 9
The Default Attribute TheDefaultAttribute
A l f d i d l i th f ll i Anexampleofderivedvaluesisthefollowing:
CLI PS> ( cl ear )
CLI PS> ( def t empl at e exampl e
( sl ot a)
( sl ot b ( t ype I NTEGER) )
( sl ot c ( al l owed- val ues r ed gr een bl ue) )
( mul t i sl ot d)
( mul t i sl ot e ( car di nal i t y 2 2)
( t ype FLOAT)
( r ange 3. 5 l 0. 0) ) )
CLI PS> ( asser t ( exampl e) )
<Fact - 0>
CLI PS> ( f act s)
f 0 ( exampl e ( a ni l )
( b 0)
( c r ed) ( )
( d)
( e 3. 5 3. 5) )
For a t ot al of 1 f act .
CLI PS> CLI PS>
SEEM 5750 10
The Default Attribute TheDefaultAttribute
If ?NONE is specified in the default attribute a value must be supplied for the slot If?NONEisspecifiedinthedefaultattribute.avaluemustbesuppliedfortheslot
whenthefactisasserted.
CLI PS> ( cl ear ) CLI PS ( cl ear )
CLI PS>
( def t empl at e exampl e
( sl ot a)
( sl ot b ( def aul t ?NONE) ) )
CLI PS> ( asser t ( exampl e) )
[ TMPLTRHS1] Sl ot b r equi r es a val ue because of i t s
( def aul t ?NONE) at t r i but e.
CLI PS> ( asser t ( exampl e ( b 1) ) )
<Fact - 0>
CLI PS> ( f act s)
f - 0( exampl e ( a ni l ) ( b 1) )
For a t ot al of 1 f act .
CLI PS>
SEEM 5750 11
The Default Attribute TheDefaultAttribute
An example using expressions with the default attribute Anexampleusingexpressionswiththedefaultattribute:
CLI PS> ( cl ear )
CLI PS>
( def t empl at e exampl e ( def t empl at e exampl e
( sl ot a ( def aul t 3) )
( sl ot b ( def aul t ( + 3 4) ) )
( mul t i sl ot c ( def aul t a b c) ) ( mul t i sl ot c ( def aul t a b c) )
( mul t i sl ot d ( def aul t ( + 1 2) ( + 3 4) ) ) )
CLI PS> ( asser t ( exampl e) )
<Fact - 0> <Fact 0>
CLI PS> ( f act s)
f - 0 ( exampl e ( a 3) ( b 7) ( c a b c) ( d 3 7) )
For a t ot al of 1 f act .
CLI PS>
SEEM 5750 12
The Deffunction Construct TheDeffunctionConstruct
f d f d h d ff Newfunctionsaredefinedusingthedeffunctionconstruct.
Thegeneralformatofadeffunctionis:
( def f unct i on <def f unct i on- name> [ <opt i onal - comment >] ( def f unct i on <def f unct i on name> [ <opt i onal comment >]
( r egul ar - par amet er >* [ <wi l dcar d- par amet er >] )
<expr essi on>*)
Where <reg lar parameter> is a single field ariable and < ildcard Where<regularparameter>isasinglefieldvariableand<wildcard
parameter>isamultifieldvariable.
Thenameofthedeffunction,<deffunctionname>,mustbedistinct.
Thebodyofthedeffunction,representedby<expression>*,isaseriesof
expressionssimilartotheRHSofarulethatareexecutedinorderwhenthe
deffunctioniscalled.
Unlikepredefinedfunctions,deffunctionscanbedeletedandthewatch
commandcanbeusedtotracetheirexecution.
SEEM 5750 13
The Deffunction Construct TheDeffunctionConstruct
h l d ild d d l i The<regularparameter>and<wildcardparameter>declarations
Specifytheargumentsthatwillbepassedintothedeffunctionwhenitis
called.
Adeffunctioncanreturnvalues.
Thereturnvalueisthatvalueofthelastexpressionevaluatedwithinthebody
of the deffunction. ofthedeffunction.
E.g.
( def f unct i on hypot enuse- l engt h ( ?a ?b)
( ** ( + ( * ?a ?a) ( * ?b ?b) ) 0. 5) )
Wherethe**functionwithitssecondargumentof0.5
computethesquareroot
(**<numericexpression><numericexpression>)isthefirstargumentraised
tothepowerofthesecondargument
SEEM 5750 14
The Deffunction Construct TheDeffunctionConstruct
b ll d f h d Itcanbecalledfromthecommandprompt:
CLI PS> ( hypot enuse- l engt h 3 4)
5. 0 5. 0
CLI PS>
Inamorereadableformat:
( def f unct i on hypot enuse- l engt h ( ?a ?b)
( bi nd ?t emp ( + ( * ?a ?a) ( * ?b ?b) ) )
( ** ?t 0 5) ) ( ** ?t emp 0. 5) )
SEEM 5750 15
The Deffunction Construct TheDeffunctionConstruct
Th R t F ti TheReturn Function
Itallowsthecurrentlyexecutingdeffunctiontobeterminated.
Itssyntaxforusewithdeffunctions:
( r et ur n [ <expr essi on>] )
If<expression>isspecified,theresultofitsevaluationisusedasthereturn
value.
E.g.
( def f unct i on hypot enuse- l engt h ( ?a ?b)
( bi nd ?t emp ( + ( * ?a ?a) ( * ?b ?b) ) )
( r et ur n ( ** ?t emp 0. 5) ) )
OR
( def f unct i on hypot enuse- l engt h ( ?a ?b)
( bi nd ?t emp ( + ( * ?a ?a) ( * ?b ?b) ) )
( bi nd ?c ( ** ?t emp 0. 5) )
( r et ur n ?c) ) ( ) )
SEEM 5750 16
The Deffunction Construct TheDeffunctionConstruct
h ff WatchingDeffunctions
Whendeffunctionsarewatchedusingwatchcommand,aninformational
messageisprintedwheneveradeffuctionbeginsorendsexecution.
CLI PS> ( wat ch def f ucnt i ons)
CLI PS> ( unwat ch def f unct i ons)
Watchspecificdeffucntions
CLI PS> ( wat ch def f ucnt i ons hypot enuse- l engt h)
CLI PS>
Wildcardparameter
Ifthelastparameterdeclaredinadeffunctionisamultifieldvariable,whichis
referred to as a wildcard parameter then the deffunction can be called with referredtoasawildcardparameter,thenthedeffunctioncanbecalledwith
moreargumentsthanarespecifiedintheparameterlist.
SEEM 5750 17
The Deffunction Construct TheDeffunctionConstruct
ff d Deffunctioncommands
Displaythetextrepresentationsofadeffunction:
(ppdeffunction<deffunctionname>) (pp )
Deleteadeffunction:
(undeffunction<deffunctionname>)
Displa the list of deff nctions defined Displaythelistofdeffunctionsdefined:
(listdeffunctions[<modulename>])
Returnsamultifieldvaluecontainningthelistofdeffucntions.
(getdeffunctionlist[<modulename>])
SEEM 5750 18
The Defglobal Construct TheDefglobalConstruct
l b l bl Globalvariables:
CLIPSallowsonetodefinevariablesthatretaintheirvaluesoutsidethescope
ofaconstruct
Localvariables:
(defruleexample1
(data1?x) ( )
=>
(printoutt?x=?xcrlf))
(defrule example1 (defruleexample 1
(data2?x)
=>
(printout t ?x = ?x crlf)) (printoutt ?x ?xcrlf))
Thevalueof?xinruleexample1doesnotconstraininanywaythevalueof?xin
ruleexample2.
SEEM 5750 19
The Defglobal Construct TheDefglobalConstruct
h l f f d f l b l Thegeneralformatofadefglobalis:
(defglobal[<defmodulename>]<globalassignment>*)
Where<globalassignment>is: g g
<globalvariable>=<expression>
And<globalvariable>is:
?*<symbol>* ? <symbol>
Globalvariablenamesbeginandendwiththe*character.
?xisalocalvariable
?* * i l b l i bl ?*x*isaglobalvariable.
E.g.
CLI PS> ( def gl obal ?*x* = 3
?*y* = ( + ?*x* 1) ) ? y = ( + ? x 1) )
CLI PS> ?*x*
3
CLI PS> ?*y*
4
CLI PS>
SEEM 5750 20
The Defglobal Construct TheDefglobalConstruct
l Example:
CLI PS> ( def r ul e ar ea
( r adi us ?r )
=>
( bi nd ?ar ea ( * ?*pi * ?*pi * ?r ) )
( pr i nt out t "Ar ea " ?ar ea cr l f ) ) ( pr i nt out t "Ar ea = " ?ar ea cr l f ) )
CLI PS> ( def f act s ar ea_ci r cl e ( r adi us 4) )
CLI PS> ( r eset )
CLI PS> ( r un)
Ar ea = 39. 47841751413609
CLI PS> CLI PS>
Thevalueofadefglobalcanbechangedusingthebindcommand.
SEEM 5750 21
Salience Salience
CLIPS provides two explicit techniques for controlling the execution of CLIPSprovidestwoexplicittechniquesforcontrollingtheexecutionof
rules:salienceandmodules.
Theuseofthekeywordsalienceallowsthepriorityofrulestobeexplicitly
specified specified.
Normallytheagendaactslikeastack.
themostrecentactivationplacedontheagendaisthefirsttofire.
Salience allows more important rules to stay at the top of the agenda Salienceallowsmoreimportantrulestostayatthetopoftheagenda,
regardlessofwhentheruleswereadded.
Salienceissetusinganumericvaluerangingfromthesmallestvalueof
10 000 to the highest of 10 000 10,000tothehighestof10,000.
Ifarulehasnosalienceexplicitlyassignedbytheprogrammer,CLIPS
assumesasalienceof0.
A newly activated rule is placed on the agenda before all rules with equal Anewlyactivatedruleisplacedontheagendabeforeallruleswithequal
orlessersalienceandafterallruleswithgreatersalience.
SEEM 5750 22
Salience Salience
No salience values are declared Nosaliencevaluesaredeclared:
( def r ul e f i r e- f i r st
( pr i or i t y f i r st )
=>
( pr i nt out t " Pr i nt f i r st " cr l f ) )
( def r ul e f i r e- second
( pr i or i t y second)
=>
( pr i nt out t " Pr i nt second" cr l f ) ) ( p ) )
( def r ul e f i r e- t hi r d
( pr i or i t y t hi r d)
=>>
( pr i nt out t " Pr i nt t hi r d" cr l f ) )
SEEM 5750 23
Salience Salience
Produce the output shown below Producetheoutputshownbelow:
CLI PS> (unwatch al l )
CLI PS> ( r eset )
CLI PS> (assert (priority f i r st ) )
<Fact - 1>
CLI PS> (assert (priority second) )
<Fact - 2>
CLI PS> (assert (priority t hi r d) )
<Fact - 3>
CLI PS> ( r un)
Pr i nt t hi r d
Pr i nt second Pr i nt second
Pr i nt f i r st
CLI PS>
SEEM 5750 24
Salience Salience
By declaring salience values Bydeclaringsaliencevalues:
( def r ul e f i r e- f i r st
( decl ar e ( sal i ence 30) )
( pr i or i t y f i r st )
=>
( pr i nt out t " Pr i nt f i r st " cr l f ) )
( def r ul e f i r e- second
( decl ar e ( sal i ence 20) )
( pr i or i t y second) ( p y )
=>
( pr i nt out t " Pr i nt second" cr l f ) )
( def r ul e f i r e- t hi r d ( def r ul e f i r e t hi r d
( decl ar e ( sal i ence 10) )
( pr i or i t y t hi r d)
=> =>
( pr i nt out t " Pr i nt t hi r d" cr l f ) )
SEEM 5750 25
Salience Salience
Produce the following output Producethefollowingoutput:
CLI PS> ( r eset )
CLI PS> ( asser t ( pr i or i t y second)
( pr i or i t y f i r st )
( pr i or i t y t hi r d) )
<Fact - 3>
CLI PS> ( agenda)
30f i r e- f i r st : f - 2
20f i r e- second: f - 1
10f i r e- t hi r d: f - 3
For a t ot al of 3 act i vat i ons.
CLI PS> CLI PS>
SEEM 5750 26
Phases and Control Facts PhasesandControlFacts
Forprogramsinvolvinghundredsorthousandsofrules,theintermixingof
domain knowledge and control knowledge makes development and domainknowledgeandcontrolknowledgemakesdevelopmentand
maintenanceamajorproblem.
Asanexample,considertheproblemofperformingfaultdetection,
isolation,andrecoveryofasystemsuchasanelectronicdevice.
DifferentPhasesforFaultDetection,Isolation,andRecoveryProblem
SEEM 5750 27
Phases and Control Facts PhasesandControlFacts
Tousesaliencetoorganizetherules, g ,
Assignmentofsaliencefordifferentphases
two major drawbacks are: twomajordrawbacksare:
controlknowledgeisstillbeingembeddedintotherulesusingsalience.
doesnotguaranteethecorrectorderofexecution.
Better approach in controlling the flow of execution is to separate the Betterapproachincontrollingtheflowofexecutionistoseparatethe
controlknowledgefromthedomainknowledge,asshowninthefollowing
figure.
each rule is given a control pattern that indicates its applicable phase eachruleisgivenacontrolpatternthatindicatesitsapplicablephase.
Controlrulesarethenwrittentotransfercontrolbetweenthedifferentphases
SEEM 5750 28
Phases and Control Facts PhasesandControlFacts
SeparationofExpertKnowledgefromControlKnowledge
SEEM 5750 29
Phases and Control Facts PhasesandControlFacts
Control rules: Controlrules:
( def r ul e det ect i on- t o- i sol at i on
( decl ar e ( sal i ence - 10) )
?phase <- ( phase det ect i on)
=>
( r et r act ?phase)
( asser t ( phase i sol at i on) ) )
( def r l e i sol at i on t o r eco er ( def r ul e i sol at i on- t o- r ecover y
( decl ar e ( sal i ence - 10) )
?phase <- ( phase i sol at i on)
=>
( r et r act ?phase)
( asser t ( phase r ecover y) ) )
( def r ul e r ecover y- t o- det ect i on
( decl ar e ( sal i ence - 10) )
?phase <- ( phase r ecover y)
=>
( r et r act ?phase) ( r et r act ?phase)
( asser t ( phase det ect i on) ) )
SEEM 5750 30
Phases and Control Facts PhasesandControlFacts
h f h l l bl f l h h l Eachoftherulesapplicableforaparticularphaseisthengivenacontrol
pattern.
( def r ul e f i nd- f aul t - l ocat i on- and- r ecover y
( phase r ecover y)
( r ecover y- sol ut i on swi t ch- devi ce
?r epl acement on)
=>
( pr i nt out t " Swi t ch devi ce" ?r epl acement " on"
cr l f ) )
Asaliencehierarchy isadescriptionofthesaliencevaluesusedbyan
expertsystem.
Each level in a salience hierarchy corresponds to a specific set of rules whose Eachlevelinasaliencehierarchycorrespondstoaspecificsetofruleswhose
membersareallgiventhesamesalience.
SEEM 5750 31
Phases and Control Facts PhasesandControlFacts
h l h f ( h d ) h f l h d Whilethefact(phasedetection)isinthefactlist,thedetectionto
isolationrulewillbeontheagenda.
Sinceithasalowersaliencethanthedetectionrules,itwillnotfireuntilallof
thedetectionruleshavehadanopportunitytofire.
Salience Hierarchy Using Expert and Control Rules SalienceHierarchyUsingExpertandControlRules
SEEM 5750 32
Phases and Control Facts PhasesandControlFacts
l l h FourLevelSalienceHierarchy
SEEM 5750 33
Misuse of Salience MisuseofSalience
Overuseofsalienceresultsinapoorlycodedprogram.
Amainadvantageofarulebasedprogramisthattheprogrammer
does not have to worry about controlling execution doesnothavetoworryaboutcontrollingexecution.
Salienceshouldprimarilybeusedasamechanismfor
determiningtheorderinwhichrulesfire. g
Salienceshouldnotbeusedasamethodforselectingasinglerule
fromagroupofruleswhenpatternscanbeusedtoexpressthe
criteria for selection criteriaforselection
SEEM 5750 34

Вам также может понравиться