问题:
我正在寻找有关类型系统的良好介绍,
基于合同/约束
(抱歉,我不记得哪个术语适合类型系统)。
我需要这些信息才能实现此类实验类型系统。
据我所知,这种类型系统用于XSD(Xml Schema Definition)。
我们不是定义数据类型,而是定义一组可能值的约束。
示例:
我定义了一些带有参数的方法,该参数要么是“nothing”,要么与整数范围[0..100]匹配。
这样的方法将接受以下值:
"nothing"
0
1
...
100
我希望,我可以清楚地表达自己。
Problem:
I am looking for good introduction about type systems,
which are based on contracts/constraints
(sorry, I don't remember which term one is appropriate for a type system).
I need that information to be able to implement an experimental type system of such kind.
As far as I know, such type system is used in XSD (Xml Schema Definition).
Instead of defining a data type, one defines constraints on the set of possible values.
Example:
I define some method with a parameter, which is either "nothing"
, or matches the integral range [0..100]
.
Such method would accept following values:
"nothing"
0
1
...
100
I hope, I could make my self clear.
发布评论
评论(3)
您可以查看 Haskell 等语言,甚至 Agda。此外,Oleg 有很多很棒的资源。
You can have a look at languages like Haskell, or even Agda. Also, Oleg has lots of great resources.
Common Lisp 在运行时提供此类类型测试。它有一个复杂的类型系统,但它的使用方式与您在静态类型语言中可能习惯的方式不同。宏
check-type
接受typespec,可以是内置的-in 规范或由宏定义的deftype
< /a>.使用类型规范表达的约束是用宿主语言编写的谓词函数的约束,也就是说,您可以在运行时检查的任何内容都可以作为构成新类型的标准。考虑这个例子:
它定义了一个名为“strange-range”的类型。现在针对它测试几个值:
最后一个会触发调试器并显示以下消息:
这个会引发相同的结果:
可以通过这种方式施加的约束是富有表现力的,但它们与复杂的类型系统的目的不同像 Haskell 或 Scala 这样的语言。虽然类型定义可以诱使 Common Lisp 编译器发出更适合操作数类型且更高效的代码,但上面的示例更多的是编写运行时类型检查的简洁方法。
Common Lisp offers such type testing at run time. It has an elaborate type system, but it's not used as you might be accustomed to in a statically-typed language. The macro
check-type
accepts a typespec, which can be a built-in specification or one defined by the macrodeftype
. The constraints expressible with typespecs are those of a predicate function written in the host language, which is to say that anything you can inspect a run time can be the criteria for what constitutes your new type.Consider this example:
That defines a type called "strange-range". Now test a few values against it:
The last one triggers the debugger with the following message:
This one provokes the same outcome:
The constraints one can impose this way are expressive, but they don't serve the same purpose that the elaborate type systems of languages like Haskell or Scala do. While type definitions can coax the Common Lisp compiler to emit code more tailored to and efficient for the types of the operands, the examples above are more of a concise way to write run-time type checks.
这不是我的专业领域,因此可能偏离主题,但 Microsoft Research 有一个项目代码契约,“提供了一种与语言无关的方式来表达 .NET 程序中的编码假设。契约采用前置条件、后置条件和对象不变量的形式”。
This is not my area of expertise, so it might be off topic, but Microsoft Research has a project Code Contracts, which "provide a language-agnostic way to express coding assumptions in .NET programs. The contracts take the form of preconditions, postconditions, and object invariants".