Prolog-iterating through list

43.9k views Asked by At

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.

1

There are 1 answers

3
Sergey Kalinichenko On BEST ANSWER

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.