Using Attribute Variables for custom type checking (at runtime)

Consider the assoc library.

One aspect of it is that it has an “initializer” for an empty assoc: empty_assoc (?Assoc)

What if i were to wrap this predicate to add an attribute variable indicating the intended type of the assoc – say, its of type ‘a->b’

new_teacher_student_mapping(Assoc) :-
    empty_assoc(Assoc)
   add_type('teacher->student', Assoc).     % adds the type symbol as attribute variable to Assoc

get_students(Assoc, Students) :-
     must_be_of_type('teacher->student', Assoc),    % raise exception, if wrong type
    assoc_to_values(Assoc, Students).

                      

Btw, this can be done without attribute variables. For example, by returning a pair instead of a vanilla assoc, and then checking for that pair.

How do these two approaches compare – e.g. performance wise.

All predicates that subsequently expect an assoc as argument could have a type check, by retrieving the assoc and checking for the expected type.

Is this something that could be done with attribute variables?

thanks,

Dan

The easiest way to add this kind of information to Prolog terms is to wrap them inside a compound.

new_teacher_student_mapping('teacher->student'(Assoc)) :-
    empty_assoc(Assoc).

You can now use syntactic unification in the head of the predicate that uses this “kind” of mapping. It will by default fail if you give it a different kind of a mapping, but I don’t want to go into that topic again.

Thanks Boris.

Sometimes, the simplest solution doesn’t occur to me :slight_smile:

Although, i think using compounds as arguments might make it harder to remove type information and testing via the term expansion approach I am now using – its a bit too built in as compound – i think.

Edit:

Also, i wonder if having compound terms passed around has a negative effect on indexing … if i recall correctly, O’Keefe in his Crafts book wasn’t too fond of using compound terms to type arguments.

Dan