Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prolog-iterating through list

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.

like image 996
Dago Avatar asked Jun 12 '15 10:06

Dago


People also ask

How do I iterate through a list in Prolog?

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).

How do you append in Prolog?

Example #1append( [X | Y], Z, [X | W]) :- append( Y, Z, W). Input: append([1,2],[3,4,5], X). In the above example of by using append, the code has been written, by performing steps append the third list from two lists, where we can say if X=[1, 2], Y=[3, 4, 5], and Z is the joining of X and Y which is the third list.

What are lists in Prolog?

Prolog in Artificial Intelligence It is a data structure that can be used in different cases for non-numeric programming. Lists are used to store the atoms as a collection. In the subsequent sections, we will discuss the following topics − Representation of lists in Prolog.


1 Answers

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.

like image 139
Sergey Kalinichenko Avatar answered Nov 10 '22 00:11

Sergey Kalinichenko