varnet
A generic approach to solve variables.
A thought to solve problems
- step1: define variables
When define a variable, need to specify: (1) which variables it depends on. (2) how to solve variable, if you know the values of variables it depends on.
- step2: instantiate some variables and get target variables.
install
npm i varnet --save
defVar and solve api
- var y = defVar(...vars, transition)
Vars are the variables y depends on.
Transition is a function, which used to solve variable. It accepts params which stand for the instances of dependent variables. The return of transition is variable's solution.
The defVar can accept zero parameters.
- var ret = solve([[variable, instance], ...], [variable, ...])
This api used to solve problem. It accepts two parameters.
First one: [[variable, instance], ...], is an array. Every item is an array too contain two elements. First element is variable, the second is the instance of the variable. The param stands for some instantiated variables.
Second one: [variable, ...] is an array. Every item is a variable. It declares which variables we want to solve. We called thoese variables as target variables.
The result of solve is an array contains the solution of every target variable.
If there is no solution (lack of variable's instance), will throw an Error.
example
- eg: solve y, y = x * x, when x is 10
var varnet = ;var defVar = varnetdefVar;var solve = varnetsolve; // define variablesvar x = ;var y = ; // solvevar ret = ; console; // [10]
- eg: solve r, z, r = w - z, z = x + y, y = x * x, when x is 5, w is 7
var varnet = ;var defVar = varnetdefVar;var solve = varnetsolve; // define variablesvar x = ;var y = ;var z = ;var w = ;var r = ; // solvevar ret = ; // [-23, 30] var ret2 = ; // [4, 6]
See, you do not need to do any composation of transition or even calculation, you just define variables, then call solve function.
domain and predicate apis
You can declare the domain of a variable, and use a couple of predicates to variable.
any
- eg: y = ∀ x ∈ X, x > 10
let x = ;let y = ; let rets = ; // [false] let rets2 = ; // [true]
- eg: ∀ x ∈ X, y ∈ [1, 5, x], x + y > 6
let x = ;let Y = ;let y = ;; let z = ;; // [true]