Consider generalizing Bounded

Philippe Sigaud philippe.sigaud at gmail.com
Wed Oct 13 13:04:40 PDT 2010


2010/10/13 Tomek Sowiński <just at ask.me>:
> It may sound ridiculous but this is what came to me in a dream last night: why exactly does
> Bounded have to express an interval? Forget intervals for a minute:
>
> struct Bounded(alias Pred, T);
>
> where Pred is a unary callable returning bool (same as in e.g. filter()).

We had a discussion 1-2 months ago on wrapping types to add
annotations. This came from Sorted!(predicate, range) which is another
example of your idea.
So I think the idea is interesting and could be generalized even
further: it's encoding external information like a contract or an
invariant in a type. Basically, creating a new, richer type from a
base type.

Ideally, we would have a generic wrapper Annotate!(Type,
someMoreInfo...), where someMoreInfo can be anything you need to
describe the new information: numbers, predicates, etc. But this comes
with a bunch of problems.

For Sorted, the (unsolved) problem was to be able to compare two
types, to see if they have 'the same' annotation.
Consider:

bool foo(int i) { return i>0;}

How can the compiler (or library writer) know whether or not
Sorted!(Range, foo) and Sorted!(Range, "a<0") are indeed the same ?

Going back to Annotate now, the difficulty is in standardizing
annotations and in combining them.
Annotate!(Annotate!(T[], hasPositiveElements), isSorted) should be the
same than
Annotate!(Annotate!(T[], isSorted), hasPositiveElements)

I found no elegant way to deal with it. One solution is to wrap each
annotation (say, in a type called Property), append them in a tuple
after the original type and sort them (maybe by name) to have an
annotation list that can be searched and compared at CT.
Like this:

Annotate!(T[], Property!(isSorted, "a<b"), Property!("a<0"))

I also remember having problems with the checking being done at
runtime, while the type is a CT entity only. Maybe I couldn't create
an enum validating or invalidating the properties, I don't rem

As jason said, this is a bit like contracts, but as you said, they are
exposed in the type. Which means they are accessible
throughcompile-time introsepction, can be changed also, extracted,
reused, etc.


> 5. work exclusively with non-null references

Except, what about a non initialized object? Can you be certain that

NonNull!(someClass) c;

is not null?


More information about the Digitalmars-d mailing list