next up previous contents
Next: Powerful Features ---Splitting Up: Powerful Features Previous: Powerful Features

Powerful Features ---Typing

Prolog is a very weakly typed language. In some sense, the only type is the term.

Not all these features are first order predicate logic. Nevertheless they give great power into the hands of the programmer.

We demonstrate their use first by defining type/2 which has mode type(+,-). It takes a term as its first argument and returns a type for the term. On redoing, it will attempt to find another type. To complicate the matter, we have specially distinguished lists ---which are compound terms.

 
type(X,variable):-

var(X),!.

type(X,atom):-

atom(X).

type(X,integer):-

integer(X).

type(X,real):-

number(X),

\+(integer(X)).

type(X,list):-

nonvar(X),

X=[__].

type(X,compound_term):-

\+(atomic(X)),

nonvar(X).

We have to use cut !/0 in the first clause because, otherwise, we can generate spurious solutions for the goal type(X,Y). There is one bug in the above ---the goal type(X,X) succeeds with X=atom! This is not really wanted. How would you guard against this?



Paul Brna
Mon May 24 20:14:48 BST 1999