Prolog type checking

2019-02-21 12:34发布

问题:

Is there a way to determine the type of an element within a list in Prolog? I know that variables aren't explicitly typed in Prolog, but I need to check whether an element is a number, a specific character, etc. How can this be accomplished?

回答1:

Prolog defines a group of built-in predicates for type testing purposes: var/1, atom/1, integer/1, float/1, atomic/1, compound/1, nonvar/1, number/1, all of them with quite a self-explanatory meaning if you know the data types of the language. For specific characters, you may exploit unification with that character, after checking that the element is not a free variable (otherwise unification is always successful).



回答2:

You could try this code:

isList([_|_]).
isList([]).

Hope it helps.



回答3:

To check if a variable is bound to a list, you can use is_list/1.



回答4:

to check list you could try:

listing(is_list/1, list_functor/1).

is_list(X) :-
    functor(X, F, _),
    list_functor(F).

list_functor('.').
list_functor('[]').


回答5:

number/1

See also http://www.swi-prolog.org/pldoc/doc_for?object=section%282,%27F.1%27,swi%28%27/doc/Manual/predsummary.html%27%29%29