Friday 15 February 2019

Prolog: Why to define facts before rules


It is always good to define facts before rules.

For example,

listDemo.pl
isList([_|Tail]) :- isList(Tail).
isList([]).


Above snippet is used to check whether given element is a list or not. As you observe above snippet, I defined the rule first, followed by the fact.

1 ?- consult(listDemo).
true.

2 ?- isList([]).
true.

3 ?- isList([1, 2]).
true.


It is working pretty good for the above examples. What if, I pass an uninstantiated variable as an argument to isList rule.

4 ?- isList(X).
ERROR: Out of local stack
   Exception: (1,763,389) isList(_10580304) ? creep
   Exception: (1,763,388) isList(_10580298) ? exit

Oops, I end up in Out of local stack error.

We can get rid of these kind of problems, if we define the fact first followed by the rules.


listDemo.pl
isList([]).
isList([_|Tail]) :- isList(Tail).

1 ?- consult(listDemo).
true.

2 ?- isList([]).
true.

3 ?- isList([1, 2]).
true.

4 ?- isList(X).
X = [] .


As you see, uninstantiated variable X is unified with [].



Previous                                                 Next                                                 Home

No comments:

Post a Comment