是否有任何编程语言都支持对原始数据类型的定义约束? [英] Does any programming language support defining constraints on primitive data types?

查看:64
本文介绍了是否有任何编程语言都支持对原始数据类型的定义约束?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

昨晚我发现编程语言可以具有一项功能,即我们应该能够约束分配给原始数据类型的值.

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.

例如,我应该可以说我的int类型变量只能具有0到100之间的值

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;

然后它将在所有情况下充当普通整数,但事实是您将无法指定约束中定义的范围之外的值.编译器将不会编译代码progress=200. 该约束可以通过类型信息来保留.

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?

推荐答案

通常是不可能的.使用没有任何算术运算符的整数几乎没有意义.使用算术运算符,您可以:

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?

如果您愿意在运行时进行检查,那么可以,从Pascal开始,几种主流语言都支持它.

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

这篇关于是否有任何编程语言都支持对原始数据类型的定义约束?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆