-
Notifications
You must be signed in to change notification settings - Fork 1
Constraint Arithmetics
Arithmetic statements are converted to constraints when possible.
//this program fails
//as the statement/constraint 'x>5' is contradicted later by 'x=1'
x>5
x=1
In general, a statement or assertion in Cosmos holds true until proven wrong. In a sense, it's the same as what relational programming already does with equality-except it's applied to the rest of arithmetic operators.
-
x>5
holds true until a statement likex=1
disproves it (x is instantiated to a value below 5). -
x=1
holds true untilx=2
orx>1
disproves it (x is either instantiated to 2 or above 1).
Logic interpretation
An arithmetic statement or definition holds true until proven otherwise.
Procedural interpretation
The constraint system takes care to store relevant statements as constraints. If the system sees that a stored constraint was contradicted, evaluation may fail.
Cosmos uses both floating-point and constraint arithmetic as its default.
A lot of constraint systems would not work well as a general-purpose arithmetic. For example, CLP(FD) is limited to integers. Thus, Cosmos uses CLP for Reals[1].
The use of floating-point arithmetic works for a high-level logic-based scripting language and we avoid the more pressing issue of mixing constraint systems.
[1] As far as we know, CLP for Reals goes back to Prolog III. See http://prolog-heritage.org/en/ph30.html. Many advances in LP that we use were already proposed in Prolog III and NU-Prolog.
In a regular language, x>5
would fail if x is not instantiated.
If x is instantiated, it should behave the same as any non-CLP language. Thus, our exploration of CLP arithmetics.
An x=1-y
expression is automatically interpreted to be a constraint. An user does not need to load any special CLP library in order to avoid using impure arithmetic. A relation in our language is pure by default.
Addition is not solely reserved for numbers. It may be used to concatenate strings, lists and arrays.
s='1'+'b'
print(s) //'1b'
print([1]+[2]) //[1,2]
The operator +
depends on type. This is not true for the other arithmetic operators.
The special functions num and str will forcefully turn an expression into a number or string. This is not entirely unlike casting. As this is generally done automatically, new code may not need to make use of these functions.
If it is not possible to do so, a runtime error is given.
print(num(x+1)) //this may lead to a runtime error, e.g. if x is not instantiated
The function int converts any floating-points to integers. This is usually done for interaction with host languages.