nools-ts
nools in TypeScript.
Nools
Nools is a rete based rules engine written entirely in javascript.
Installation
npm i nools-ts
Dev
- Clone source from Github, or download source code.
$ git clone git@github.com:taoqf/nools-ts.git
- Switch to branch functional
$ git checkout functional
- Install gulp
$ npm install gulp -g
- Build
$ npm install
- Test
$ gulp
Usage
- Flows
- Defining A Flow
- Sessions
- Facts
- Firing
- Disposing
- Removing A Flow
- Removing All Flows
- Checking If A Flow Exists
- Agenda Group
- Conflict Resolution
- Defining Rules
- Browser Support
- Fibonacci
Resources
Defining a flow
When using nools you define a flow which acts as a container for rules that can later be used to get a session
Programmatically
var nools = ; var { thistext = message;}; var flow = nools;
In the above flow definition 2 rules were defined
- Hello
- Requires a Message
- The messages's
text
must match the regular expression/^hello\\sworld$/
- When matched the message's
text
is modified and then we let the engine know that we modified the message.
- Goodbye
- Requires a Message
- The messages's
text
must match the regular expression/.*goodbye$/
(anything that ends in goodbye) - When matched the resulting message is logged.
DSL
You may also use the nools
rules language to define your rules.
The following is the equivalent of the rules defined programmatically above.
define Message {
text : '',
constructor : function(message){
this.text = message;
}
}
//find any message that starts with hello
rule Hello {
when {
m : Message m.text =~ /^hello(\s*world)?$/;
}
then {
modify(m, function(){this.text += " goodbye";});
}
}
//find all messages then end in goodbye
rule Goodbye {
when {
m : Message m.text =~ /.*goodbye$/;
}
then {
console.log(m.text);
}
}
To use the flow
var flow = nools Message = flow;
Flow Events
Each flow can have the following events emitted.
assert (fact)
- emitted when facts are assertedretract (fact)
- emitted when facts are retractedmodify (fact)
- emitted when facts are modifiedfire (name, rule)
- emitted when an activation is fired.
session.on("assert", function(fact){
//fact was asserted
});
session.on("retract", function(fact){
//fact was retracted
});
session.on("modify", function(fact){
//fact was modifed
});
session.on("fire", function(name, rule){
//a rule was fired.
});
nools.compile
The compile method accepts the following parameters
source|path
- The first argument must either be a path that ends in.nools
or a string which is the source of the rules that you wish to compile.options?
name
: This is the name of the flow. You can use this name to look up the flow by usingnools.getFlow
.define
: A hash of Classes that should be aviable to the rules that you are compiling.scope
: A hash of items that should be available to rules as they run. (i.e. a logger)
cb?
- an options function to invoke when compiling is done.
Example
rule "person name is bob" {
when {
p : Person p.name == 'bob';
}
then {
logger.info("Found person with name of bob");
retract(p);
}
}
In the above rules file we make use of a Person class and a logger. In order for nools to properly reference the Class and logger you must specify them in your options.
var flow = nools;
You may also compile source directly.
var noolsSource = "rule 'person name is bob' {" + " when {" + " p : Person p.name == 'bob';" + " }" + " then {" + " logger.info('Found person with name of bob');" + " retract(p);" + " }" + "}"; var flow = nools;
Working with a session
A session is an instance of the flow that contains a working memory and handles the assertion, modification, and retraction of facts from the engine.
To obtain an engine session from the flow invoke the getSession
method.
var session = flow;
Working with facts
Facts are items that the rules should try to match.
Assert
To add facts to the session use assert
method.
session;session;session;
As a convenience any object passed into getSession will also be asserted.
Note assert is typically used pre engine execution and during the execution of the rules.
flow;
Retract
To remove facts from the session use the retract
method.
var m = "hello"; //assert the fact into the enginesession; //remove the fact from the enginesession;
Note retract
is typically used during the execution of the rules.
Modify
To modify a fact use the modify
method.
Note modify will not work with immutable objects (i.e. strings).
var m = "hello"; session; mtext = "hello goodbye"; session;
Note modify
is typically used during the execution of the rules.
Retrieving Facts
To get a list of facts currently in the session you can use the getFacts()
method exposed on a session.
session;session;session;session; session; //[1, "A", "B", 2];
You may also pass in a Type
to getFacts
which will return facts only of the given type.
session;session;session;session; session; //[1, 2];session; //["A", "B"];
Firing the rules
When you get a session from a flow no rules will be fired until the match method is called.
var session = flow;//assert your different messagessession;session;session; //now fire the rulessession
The match method also returns a promise that is resolved once there are no more rules to activate.
session;
Fire until halt
You may also run the engine an a "reactive" mode which will continue to match until halt
is invoked.
In the following example the rules engine continues to evaluate until the counter reaches 10000
. If you remove the "counted to high" rule then the engine would run indefinitely.
define Counter count: 0 { thiscount = count; } //We reached our goalrule "I can count!" when $ctr: Counter $ctrcount == 10000; then console; ; //no counter was asserted so create onerule "not count" when ; then console; ; //A little status updaterule "give them an update" when $ctr: Counter $ctrcount % 1000 == 0 count: $count then console; ; //just counting awayrule count when $ctr: Counter count: $count then ;
flow;
matchUntilHalt
also returns a promise.
flow ;
Disposing of the session
When working with a lot of facts it is wise to call the dispose
method which will purge the current session of
all facts, this will help prevent the process from growing a large memory footprint.
session;
Removing a flow
To remove a defined flow from nools
use the deleteFlow
function.
var myFlow = nools; nools; //returns nools for chaining nools; //undefined
You may also remove a flow using the FlowContainer
object returned from nools.flow;
var myFlow = nools; nools; //returns nools for chaining nools; //undefined
Removing All Flows
To remove all flow from nools
use the deleteFlows
function.
var myFlow = nools; nools; //returns nools for chaining nools; //undefined
Checking If A Flow Exists
To check if a flow currently is registering with nools
use the hasFlow
function;
var myFlow = nools; nools; //true
Agenda Groups
Agenda groups allow for logical groups of rules within a flow.
The agenda manages a stack
of agenda-groups
that are currently in focus. The default agenda-group
is called main
and all rules that do not have an agenda-group
specified are placed into the main
agenda-group
.
As rules are fired and a particular agenda-group
runs out of activations then that agenda-group
is popped from the internal agenda-group
stack and the next one comes into focus. This continues until focus
is explicitly called again or the main
agenda-group
comes into focus.
Note Once an agenda group loses focus it must be re-added to the stack in order for those activations to be focused again.
To add a rule to an agenda-group you can use the agendaGroup
option.
this; this;
Or in the dsl
rule "Hello World" {
agenda-group: "ag1";
when{
m : Message m.name === 'hello';
}
then{
modify(m, function(){
this.name = "goodbye";
});
}
}
rule "Hello World 2" {
agenda-group: "ag2";
when{
m : Message m.name === 'goodbye';
}
then {
modify(m, function(){
m.name = "hello";
});
}
}
In the above rules we have defined two agenda-groups called ag1
and ag2
Focus
When running your rules and you want a particular agenda group to run you must call focus
on the session of the flow and specify the agenda-group
to add to the stack.
//assuming a flow with the rules specified above.
var fired = [];
flow.getSession(new Message("hello"))
.focus("ag1")
.on("fire", function (ruleName) {
fired.push(ruleName);
})
.match(function () {
console.log(fired); //[ 'Hello World' ]
});
Or you can add multiple agenda-groups
to the focus stack.
var fired1 = fired2 = ;flow ;flow ;
Notice above that the last agenda-group
focused is added to the array first.
Auto Focus
Sometimes you may want an agenda-group
to auto-focus
whenever a certain rule is activated.
this.rule("Bootstrap", [State, "a", "a.name == 'A' && a.state == 'NOT_RUN'"], function (facts) {
this.modify(facts.a, function () {
this.state = 'FINISHED';
});
});
this.rule("A to B",
[
[State, "a", "a.name == 'A' && a.state == 'FINISHED'"],
[State, "b", "b.name == 'B' && b.state == 'NOT_RUN'"]
],
function (facts) {
this.modify(facts.b, function () {
this.state = "FINISHED";
});
});
this.rule("B to C",
{agendaGroup: "B to C", autoFocus: true},
[
[State, "b", "b.name == 'B' && b.state == 'FINISHED'"],
[State, "c", "c.name == 'C' && c.state == 'NOT_RUN'"]
],
function (facts) {
this.modify(facts.c, function () {
this.state = 'FINISHED';
});
this.focus("B to D");
});
this.rule("B to D",
{agendaGroup: "B to D"},
[
[State, "b", "b.name == 'B' && b.state == 'FINISHED'"],
[State, "d", "d.name == 'D' && d.state == 'NOT_RUN'"]
],
function (facts) {
this.modify(facts.d, function () {
this.state = 'FINISHED';
});
});
Or using the dsl
rule Bootstrap {
when{
a : State a.name == 'A' && a.state == 'NOT_RUN';
}
then{
modify(a, function(){
this.state = 'FINISHED';
});
}
}
rule 'A to B' {
when{
a : State a.name == 'A' && a.state == 'FINISHED';
b : State b.name == 'B' && b.state == 'NOT_RUN';
}
then{
modify(b, function(){
this.state = 'FINISHED';
});
}
}
rule 'B to C' {
agenda-group: 'B to C';
auto-focus: true;
when{
b: State b.name == 'B' && b.state == 'FINISHED';
c : State c.name == 'C' && c.state == 'NOT_RUN';
}
then{
modify(c, function(){
this.state = 'FINISHED';
});
focus('B to D')
}
}
rule 'B to D' {
agenda-group: 'B to D';
when{
b: State b.name == 'B' && b.state == 'FINISHED';
d : State d.name == 'D' && d.state == 'NOT_RUN';
}
then{
modify(d, function(){
this.state = 'FINISHED';
});
}
}
In the above rules we created a state machine that has a rule with auto-focus
set to true.
This allows you to not have to specify focus
when running the flow.
var fired = ;flow ;
Conflict Resolution
When declaring a flow it is defined with a default conflict resolution strategy. A conflict resolution strategy is used to determine which rule to activate when multiple rules are ready to be activated at the same time.
Resolution Strategies
salience
- sort activations on the specifiedsalience
. (NOTE The default salience of a rule is 0).activationRecency
- sort activations on activation recency. This is aLIFO
strategy the latest activation takes precedence.factRecency
- sort activations based onfact
recency. Each time a fact isasserted
ormodified
its recency is incremented.bucketCounter
- sort activations on the internalbucket
counter. The bucket counter is incremented after an activation is fired and the internalworkingMemory
is altered.factRecencyInverse
- sort activations by the oldest fact first. This is aFIFO
strategy, the earliest fact takes precedence.
The default conflict resolution strategy consists of salience
and activationRecency
.
Examples
Example 1
//activation 1
{
salience: 0,
activationRecency: 1
}
//activation 2
{
salience: 0,
activationRecency: 2
}
In the above example activation 2 would be fired since it is the most recent activation and the rule salience is the same.
Example 2
//activation 1
{
salience: 1,
activationRecency: 1
}
//activation 2
{
salience: 0,
activationRecency: 2
}
In this example activation 1 would fire because it has a greater salience
Overidding The Default Strategy
To override the default strategy you can use the conflictResolution
method on a flow.
var flow = nools; flow;
The combination of salience
, factRecency
, and activationRecency
would do the following.
- Check if the salience is the same, if not use the activation with the greatest salience.
- If salience is the same check if fact recency is the same. The fact recency is determined by looping through the facts in each activation and until two different recencies are found. The activation with the greatest recency takes precendence.
- If fact recency is the same check the activation recency.
Example 1
//activation 1
{
salience: 2,
factRecency: [1,2,3],
activationRecency: 1
}
//activation 2
{
salience: 1,
factRecency: [1,2,4],
activationRecency: 2
}
In this example activation 1 would fire because it's salience is the greatest.
Example 2
//activation 1
{
salience: 1,
factRecency: [1,2,3],
activationRecency: 1
}
//activation 2
{
salience: 1,
factRecency: [1,2,4],
activationRecency: 2
}
In Example 2 activation 2 would fire because of the third recency entry.
Example 3
//activation 1
{
salience: 2,
factRecency: [1,2,3],
activationRecency: 1
}
//activation 2
{
salience: 1,
factRecency: [1,2,3],
activationRecency: 2
}
In Example 3 activation 2 would fire because salience
and factRecency
are the same but activation 2's activation recency is greater.
Defining rules
Rule structure
Lets look at the "Calculate" rule in the Fibonacci example
//flow.rule(type[String|Function], constraints[Array|Array[[]]], action[Function]); flow;
Or using the nools DSL
rule Calculate{
when {
f1 : Fibonacci f1.value != -1 {sequence:s1};
f2 : Fibonacci f2.value != -1 && f2.sequence == s1 + 1 {sequence:s2};
f3 : Fibonacci f3.value == -1 && f3.sequence == s2 + 1;
}
then {
modify(f3, function(){
this.value = f1.value + f2.value;
});
retract(f1);
}
}
Salience
Salience is an option that can be specified on a rule giving it a priority and allowing the developer some control over conflict resolution of activations.
this; this; this; this;
Or using the DSL
rule Hello4 salience: 7; when m: Message mname == 'hello'; then {} rule Hello3 salience: 8; when m: Message mname == 'hello'; then {} rule Hello2 salience: 9; when m: Message mname == 'hello'; then {} rule Hello1 salience: 10; when m: Message mname == 'hello'; then {}
In the above flow we define four rules each with a different salience, when a single message is asserted they will fire in order of salience (highest to lowest).
var fired = ;flow1 ;
Scope
Scope allows you to access function from within your rules.
If you are using vanilla JS you can use the scope
option when defining your rule.
this;
If you are using the dsl.
function matches(str, regex){
return regex.test(str);
}
rule Hello {
when {
m : Message matches(m.text, /^hello\s*world)?$/);
}
then {
modify(m, function(){
this.text += " goodbye";
})
}
}
rule Goodbye {
when {
m : Message matches(m.text, /.*goodbye$/);
}
then {
}
}
Or you can pass in a custom function using the scope option in compile.
rule Hello {
when {
m : Message doesMatch(m.text, /^hello\sworld$/);
}
then {
modify(m, function(){
this.text += " goodbye";
})
}
}
rule Goodbye {
when {
m : Message doesMatch(m.text, /.*goodbye$/);
}
then {
}
}
Provided the doesMatch
function in the scope option of compile.
{ return regex;};var flow = nools;
Constraints
Constraints define what facts the rule should match. The constraint is a array of either a single constraint (i.e. Bootstrap rule) or an array of constraints(i.e. Calculate).
Programmatically
//Type alias pattern store sequence to s1 Fibonacci "f1" "f1.value != -1" sequence:"s1" Fibonacci "f2" "f2.value != -1 && f2.sequence == s1 + 1" sequence:"s2" Fibonacci "f3" "f3.value == -1 && f3.sequence == s2 + 1" Result "r"
Using nools DSL
when {
f1 : Fibonacci f1.value != -1 {sequence:s1};
f2 : Fibonacci f2.value != -1 && f2.sequence == s1 + 1 {sequence:s2};
f3 : Fibonacci f3.value == -1 && f3.sequence == s2 + 1;
r : Result;
}
-
Type - is the Object type the rule should match. The available types are
String
- "string", "String", StringNumber
- "number", "Number", NumberBoolean
- "boolean", "Boolean", BooleanDate
- "date", "Date", DateRegExp
- "regexp", "RegExp", RegExpArray
- "array", "Array", [], ArrayObject
- "object", "Object", "hash", Object- Custom - any custom type that you define
-
Alias - the name the object should be represented as.
-
Pattern(optional) - The pattern that should evaluate to a boolean, the alias that was used should be used to reference the object in the pattern. Strings should be in single quotes, regular expressions are allowed. Any previously defined alias/reference can be used within the pattern. Available operators are.
&&
,AND
,and
||
,OR
,or
>
,<
,>=
,<=
,gt
,lt
,gte
,lte
==
,===
,!=
,!==
,=~
,!=~
,eq
,seq
,neq
,sneq
,like
,notLike
+
,-
,*
,/
,%
-
(unary minus).
(member operator)in
(check inclusion in an array)notIn
(check that something is not in an array)- Defined helper functions
now
- the current dateDate(year?, month?, day?, hour?, minute?, second?, ms?)
- creates a newDate
objectlengthOf(arr, length)
- checks the length of an arrayisTrue(something)
- check if something === trueisFalse(something)
- check if something === falseisRegExp(something)
- check if something is aRegExp
isArray(something)
- check if something is anArray
isNumber(something)
- check if something is anNumber
isHash(something)
- check if something is strictly anObject
isObject(something)
- check if something is any type ofObject
isDate(something)
- check if something is aDate
isBoolean(something)
- check if something is aBoolean
isString(something)
- check if something is aString
isUndefined(something)
- check if something is aundefined
isDefined(something)
- check if something isDefined
isUndefinedOrNull(something)
- check if something is aundefined
ornull
isPromiseLike(something)
- check if something is a "promise" like (containingthen
,addCallback
,addErrback
)isFunction(something)
- check if something is aFunction
isNull(something)
- check if something isnull
isNotNull(something)
- check if something is not nulldateCmp(dt1, dt2)
- compares two dates return 1, -1, or 0(years|months|days|hours|minutes|seconds)(Ago|FromNow)(interval)
- adds/subtracts the date unit from the current time
-
Reference(optional) - An object where the keys are properties on the current object, and values are aliases to use. The alias may be used in succeeding patterns.
Custom Constraint
When declaring your rules progrmmatically you can also use a function as a constraint. The function will be called with an object containing each fact that has matched previous constraints.
var HelloFact = ; var flow = nools; var session = flow;session;session;session;
Not Constraint
The not
constraint allows you to check that particular fact
does not exist.
Number "n1" "not" Number "n2" "n1 > n2"
Or using the DSL.
when {
n1: Number;
not(n2: Number n1 > n2);
}
The previous example will check that for all numbers in the workingMemory
there is not one that is greater than n1
.
Or Constraint
The or
constraint can be used to check for the existence of multiple facts.
"or" String "s" "s == 'hello'" String "s" "s == 'world'" String "s" "s == 'hello world'"
Using the DSL.
when {
or(
s : String s == 'hello',
s : String s == 'world',
s : String s == 'hello world'
);
}
The previous example will evaluate to true
if you have a string in workingMemory
that equals hello
, world, or 'hello world
.
Or with Not
The or
constraint can be combined with a not
constraint to allow for the checking of multiple not conditions without the implcit and.
var flow = nools;});
or using the dsl.
rule MultiNotOrRule {
when {
or (
not(n1: Number n1 == 1),
not(s1: String s1 == 'hello'),
not(d1: Date d1.getDate() == now().getDate())
);
c: Count;
}
then{
c.called++;
}
}
Note Using the or
with a not
will cause the activation to fire for each not
condition that passes. In the above examples if none of the three facts existed then the rule would fire three times.
From Constraint
The from
modifier allows for the checking of facts that are not necessarily in the workingMemory
.
The from
modifier can be used to access properties on a fact
in workingMemory
or you can use javascript expressions.
To access properties on a fact you can use the fact name and the property you wish to use as the source for the from
source.
Person "p" Address "a" "a.zipcode == 88847" "from p.address" String "first" "first == 'bob'" "from p.firstName" String "last" "last == 'yukon'" "from p.lastName"
Or using the DSL.
when {
p: Person:
a: Address a.zipcode == 88847 from p.address;
first: String first == 'bob' from p.firstName;
last: String last == 'yukon' from p.lastName;
}
The above example will used the address, firstName and lastName from the person
fact.
You can also use the from
modifier to check facts that create a graph.
For example assume the person object from above has friends that are also of type Person
.
Person "p" Person "friend" "friend.firstName != p.firstName" "from p.friends" String "first" "first =~ /^a/" "from friend.firstName"
Or using the DSL.
when {
p: Person;
friend: Person friend.firstName != p.firstName from p.friends;
first: String first =~ /^a/ from friend.firstName;
}
The above example will pull the friend
fact from the friends array property on fact p
, and first from the friend
's firstName
.
You could achieve the same thing using the following code if you assert all friends into working memory.
when {
p: Person;
friend: Person friend in p.friends && friend.firstName != p.firstName && p.firstName =~ /^a/;
}
To specify the from source as an expression you can do the following.
Number "n1" "from [1,2,3,4,5]"
Or using the dsl
{
n1: Number from [1,2,3,4,5];
}
Using the above syntax you could use from
to bootstrap data.
You can also use any function defined in the scope of the rule
or flow
flow
Or using the dsl and the scope option.
rule "my rule", {
when {
n1: Number from myArr();
}
then{
assert(n1);
}
}
Exists Constraint
exists
is the logical inversion of a not
constraint. It checks for the existence of a fact in memory.
NOTE If there are multiple facts that satisfy the constraint the rule will ONLY be fired once.
"exists" Number "n1" "n1 > 1"
Or using the DSL.
when {
exists(n1: Number n1 > 1);
}
Assuming the above constraint. The following facts would cause the rule to fire once since there is a number that is greater than 1.
session;session;session;session;session;
Action
The action is a function that should be fired when all patterns in the rule match. The action is called in the scope
of the engine so you can use this
to assert
, modify
, or retract
facts. An object containing all facts and
references created by the alpha nodes is passed in as the first argument to the action.
So calculate's action modifies f3 by adding the value of f1 and f2 together and modifies f3 and retracts f1.
{ var f3 = factsf3 f1 = factsf1 f2 = factsf2; var v = f3value = f1value + factsf2value; factsrresult = v; this; this; }
The session is also passed in as a second argument so alternatively you could do the following.
{ var f3 = factsf3 f1 = factsf1 f2 = factsf2; var v = f3value = f1value + factsf2value; factsrresult = v; session; session; }
To define the actions with the nools DSL
then {
modify(f3, function(){
this.value = f1.value + f2.value;
});
retract(f1);
}
For rules defined using the rules language nools will automatically determine what parameters need to be passed in based on what is referenced in the action.
Async Actions
If your action is async you can use the third argument which should be called when the action is completed.
{ //some async action process; }
If an error occurs you can pass the error as the first argument to next
.
then ;
If you are using a Promises/A+
compliant library you can just return a promise from your action and nools
will wait for the promise to resolve before continuing.
then return ; // assume saveToDatabase returns a promise
Globals
Globals are accessible through the current working scope of rules defined in a dsl
, very similar to using the scope
option when compiling.
Note globals
are not part of the working memory and therefore are not accessible in the LHS (when) or your rule.
Globals are used like the following:
global PI = Math.PI;
global SOME_STRING = 'some string';
global TRUE = true;
global NUM = 1.23;
global DATE = new Date();
rule "A Rule" {
when {
$obj: Object;
}
then{
console.log(PI); //Math.PI;
console.log(SOME_STRING); //"some string"
console.log(TRUE); //true
console.log(NUM); //1.23
console.log(DATE); //Thu May 23 2013 15:49:22 GMT-0500 (CDT)
}
}
If you are using nools
in node
you can also use a require statement.
NOTE require does not currently work for relative paths.
global util = require("util");
rule "A Rule" {
when {
$obj: Object;
}
then{
util.log("HELLO WORLD");
}
}
Importing
The import
statement allows you to import other nools
files into the current one. This can be used to split up logical flows into small reusable groups of rules.
Define our common model to be used across our flows.
//define.nools
define Count{
constructor: function(){
this.called = 0;
}
}
Create a rules file which imports the define.nools
to define our Count
model.
//orRule.nools
//import define.nools
import("./define.nools");
rule orRule {
when {
or(
s : String s == 'hello',
s : String s == 'world'
);
count : Count;
}
then {
count.called++;
count.s = s;
}
}
Same as orRule.nools
import our define.nools
//notRule.nools
import("./defines.nools");
rule notRule {
when {
not(s : String s == 'hello');
count : Count
}
then {
count.called++;
}
}
Now we can use orRule.nools
and notRule.nools
to compose a new flow that contains define.nools
, orRule.nools
and notRule.nools
.
Note nools
will handle duplicate imports, in this case define.nools
will only be imported once.
//import
import("./orRules.nools");
import("./notRules.nools");
Emitting custom events.
You may also emit events from your rule actions using the sessions emit function.
then {
modify(f3, function(){
this.value = f1.value + f2.value;
});
retract(f1);
emit("my custom event");
}
To listen to the event just use the on method of the session.
var session = flow.getSession();
session.on("my custom event", function(){
//custom event called.
});
Browser Support
Nools
can also be used in the browser. The only difference is that you cannot pass a file location to the compile method instead you must provide the source.
Nools is compatible with amd(requirejs) and can also be used in a standard script tag.
Example 1.
In this example we compile rules definitions inlined in a script tag.
Using a compiled dsl.
You may also use the nools
executable to compile source into a browser friendly format skipping the need for compiling each time.
nools compile ./my/rules.nools > ./compiled.js
To use the flow require the compile version either through a script tag, amd/requirejs
, or commonjs
require.
If you import the flow using a script tag you can get a reference to the flow by using nools.getFlow
.
nools.getFlow("rules");
You may also specify the name of the flow when compiling, it defaults to the name of the nools file less ".nools"
nools compile -n "my rules" ./my/rules.nools
nools.getFlow("my rules");
If you are using requirejs or nools must be required using something other than require("nools")
then you can specify a location of the nools source.
nools compile -nl "./location/to/nools" ./my/rules.nools
RequireJS examples
Examples of using nools with require js are located in the examples directory.
Examples
Fibonacci
"use strict"; var nools = ; var { thissequence = sequence; thisvalue = value || -1;}; var { thisresult = result || -1;}; var flow = nools; var r1 = session1 = flow s1 = ;session1; var r2 = session2 = flow s2 = ;session2; var r3 = session3 = flow s3 = ;session3;
Output
55 [43ms]
9.969216677189305e+30 [383ms]
4.346655768693743e+208 [3580ms]
Fibonacci with nools DSL
//Define our object classes, you can
//also declare these outside of the nools
//file by passing them into the compile method
define Fibonacci {
value:-1,
sequence:null
}
define Result {
value : -1
}
rule Recurse {
when {
//you can use not or or methods in here
not(f : Fibonacci f.sequence == 1);
//f1 is how you can reference the fact else where
f1 : Fibonacci f1.sequence != 1;
}
then {
assert(new Fibonacci({sequence : f1.sequence - 1}));
}
}
rule Bootstrap {
when {
f : Fibonacci f.value == -1 && (f.sequence == 1 || f.sequence == 2);
}
then{
modify(f, function(){
this.value = 1;
});
}
}
rule Calculate {
when {
f1 : Fibonacci f1.value != -1 {sequence : s1};
//here we define constraints along with a hash so you can reference sequence
//as s2 else where
f2 : Fibonacci f2.value != -1 && f2.sequence == s1 + 1 {sequence:s2};
f3 : Fibonacci f3.value == -1 && f3.sequence == s2 + 1;
r : Result
}
then {
modify(f3, function(){
this.value = r.result = f1.value + f2.value;
});
retract(f1);
}
}
And to run
var flow = nools; var Fibonacci = flow Result = flow;var r1 = session1 = flow s1 = +;session1; var r2 = session2 = flow s2 = +;session2; var r3 = session3 = flow s3 = +;session3;
License
MIT https://github.com/taoqf/nools-ts/blob/master/LICENSE
Meta
- Code:
git clone git@github.com:taoqf/nools-ts.git
- Code:
git clone https://github.com/taoqf/nools-ts.git