So let's say we have the next facts:
(deffacts p
(fa x)
(fa y)
(fa z)
(ba a)
(ba b)
)
and the rule:
(defrule dance
(ba ?ba)
(fa ?fa)
=>
(printout t ?ba ?fa crlf)
)
The output will be bz by bx az ay ax
but if we move the last two facts above the first three the output will change to
az bz ay by ax bx
Why is this happening? what is the logic behind?
In declarative programming, you specify what you want done, but otherwise leave the details unspecified. For example, if you told someone to move all of the boxes from the attic to the basement, there's lots of ways that can be done. It shouldn't be surprising after the move that the boxes were kept in the same stacks from back to front or that the stacks were inverted and the ones previously at the front were now at the back.
All your rule specifies is that all combinations of values from the ba and fa facts are printed. The order in which that should be done is not specified, so the pattern matching algorithm determines that order for you. For practical purposes, it's useful for that ordering to be deterministic even if parts of it are arbitrary. The technical term used for the process of determining the order in which rules should be fired if there are multiple rules that can be applied is called the conflict resolution strategy. In CLIPS, rules activated by more recent facts are executed first. Since (ba b) is initially the last fact asserted by your deffacts, the activations for (ba b) are executed first and then the activations for (ba a). When you place the ba facts first in your deffacts, it's the latter fa facts which activate the rules. Since (fa z) was asserted last, the activations for it are executed first, following by the activations for (fa y), and then finally (fa x).