Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does any programming language support defining constraints on primitive data types?

Last night I was thining that programming languages can have a feature in which we should be able to constraints the values assigned to primitive data types.

For example I should be able to say my variable of type int can only have value between 0 and 100

int<0, 100> progress;

This would then act as a normal integer in all scenarios except the fact that you won't be able to specify values out of the range defined in constraint. The compiler will not compile the code progress=200. This constraint can be carried over with type information.

Is this possible? Is it done in any programming language? If yes then which language has it and what is this technique called?

like image 215
Muhammad Hasan Khan Avatar asked Jun 21 '11 08:06

Muhammad Hasan Khan


1 Answers

It is generally not possible. It makes little sense to use integers without any arithmetic operators. With arithmetic operators you have this:

int<0,100> x, u, v;
...
x = u + v; // is it in range?

If you're willing to do checks at run-time, then yes, several mainstream languages support it, starting with Pascal.

like image 181
n. 1.8e9-where's-my-share m. Avatar answered Oct 27 '22 17:10

n. 1.8e9-where's-my-share m.