Arash Taher

Prolog: How to implement if-then structure

How to implement if-then-else in Prolog? This was a question posted on Stack Overflow, and I thought it might be good to say a few words about it here.

There is nothing like ‘if’ or ’else’ in logical programming languages. All you have are some rules and facts :) Your job as a programmer in this environment is not to tell the language how to do the thing (if foo then bar), but to describe the problem. You state some facts, establish some rules, and based on that (unification), the language interpreter will search and find the solutions for any given problem that fits into your description (backtrack).

Suppose we want to find the union of two sets. How do we make decisions? Let’s see:

union([], X, X).
union([H|T], X, List) :- member(H, X), union(T, X, List), !.
union([H|T], X, [H|List]) :- union(T, X, List).

You can see we did not use conditions; we just set up different rules for different conditions. As another example, take a look at this code. Here we want to exclude all the elements of the first list from the second one. We have no condition:

diffLst(_, [], []).
diffLst([], X, X).
diffLst([H|T], [H|Rest], Result) :- diffLst(T, Rest, Result). % Ignore same items
diffLst(Exc, [I|Rest], [I|Result]) :- [H|_] = Exc, H > I, diffLst(Exc, Rest, Result).
diffLst([H|T], Inc, Result) :- [I|_] = Inc, H < I, diffLst(T, Inc, Result).

That’s the stuff, isn’t it?

#Concept #Programming #Prolog