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.
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.