Prolog-iterating through list

Dago picture Dago · Jun 12, 2015 · Viewed 29.5k times · Source

Let's say i have list Xs = [a,b,c]. Now i want to iterate through all elements and call another function for this elements. My question is: how to do this using head and tail? I would be grateful for help.

Answer

Sergey Kalinichenko picture Sergey Kalinichenko · Jun 12, 2015

Generally, you do not iterate in Prolog. Instead, you write a rule with a pair of recursive clauses, like this:

 dosomething([]).
 dosomething([H|T]) :- process(H), dosomething(T).

The first clause processes the base case, when the list [] is empty. In this case, there is nothing to do, so the body of the rule is empty as well.

The second clause processes the case when your list has at least one element. Syntax [H|T] unifies with your list in such a way that H becomes the head of the list, and T becomes its tail. For example, if you process dosomething([a,b,c]), H becomes a, and T becomes [b,c].

The body of this rule has two parts. The first part operates on the head, calling process on it. This is the rule that you want executed for each element of the list. The second part invokes dosomething rule recursively on the tail of the list. When the tail list is not empty, the second clause of dosomething would unify with the shorter list to continue processing. When the tail list is empty, the first clause would unify, thus ending the processing.