[rules-users] Use of the binding variable
Davide Sottara
dsotty at gmail.com
Thu May 9 13:49:46 EDT 2013
The unification operator ":=" is a combination of the binding operator
":" and the equality operator "==".
In fact, it behaves as either, depending on the context:
In this example, we are looking for two different Persons with the same
name:
rule "Pairs"
when
$p := Person( $name := name )
Person( this != $p, $name := name )
then
System.out.println( "We have two persons with the same name : " +
$name );
end
The LHS is equivalent to:
$p : Person( $name : name )
Person( this != $p, name == $name )
The first time a variable such as $name is used with ":=", it works as
":". Any time later, since the
variable now has a value assigned to it, ":=" will work as "==".
Apparently, this operator may seem redundant and useless :) but it is
actually meant to be used
with **queries**. For example:
query personsByName( String $name, Person $p )
$p := Person( $name := name )
end
The arguments ($name, $p) can be BOTH IN and OUT parameters, depending
on the context of
the caller. So, the query can be used in 4 different ways:
IN/IN : Is this Person in the WM and does it have this name?
?personsByName( "john", p1 )
IN/OUT : Retrieve all Persons with this name
?personsByName( "john", $pers )
OUT/IN : Retrieve this person, if it is in the WM, and return its name
?personsByName( $n, p1 )
OUT/OUT : Retrieve all persons from the WM with their names
?personsByName( $n, $pers )
Fir this reason, it is impossible for the query to know whether, upon
invocation, $name and $p
will be IN - and thus already have a value - or OUT. So, the unification
operator ":=" is necessary
because of its polymorphic ability to behave as ":" or "==" as appropriate.
Best
Davide
On 05/09/2013 06:51 AM, Sonata wrote:
> Hi, it would be the same question: How would you use :=? Any use case?
> Situation? Good example?
>
> I know I can use := in functions as a return parameter to be used in the
> "then" part.
> But thats the only use case I can think of.
>
> Thank you
>
>
>
> --
> View this message in context: http://drools.46999.n3.nabble.com/Use-of-the-binding-variable-tp4023744p4023751.html
> Sent from the Drools: User forum mailing list archive at Nabble.com.
> _______________________________________________
> rules-users mailing list
> rules-users at lists.jboss.org
> https://lists.jboss.org/mailman/listinfo/rules-users
>
More information about the rules-users
mailing list