9

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.

Dago
  • 788
  • 2
  • 9
  • 24
  • For one thing map is your friend – therealprashant Jun 12 '15 at 10:13
  • If you remove the restriction of `head` and `tail`, you can do looping through list elements simply by using `fail` and disjunction: `member(X, [1,2,3,4]), writeln(X), fail; true.` will print the list elements one by one and the goal will succeed. – Fibo Kowalsky Jan 20 '19 at 16:03

1 Answers1

27

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.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • 11
    While this answer is correct, it is very 1970s. In the meantime, there is [`maplist(process, [a,b,c])`](http://stackoverflow.com/a/30759136/772868), and [`maplist/3`, `maplist/4` ...](http://stackoverflow.com/a/6683502/772868) – false Jun 12 '15 at 12:09
  • 9
    @false You are absolutely right. However, OP wanted to know "how to do this using head and tail", so I explained the 1970s way of doing it. I think that solid understanding of this simple code snippet is very important to understanding Prolog's way of doing things. Of course Prolog practitioners quickly discover `maplist/2`, and they never go back . – Sergey Kalinichenko Jun 12 '15 at 12:17
  • 2
    Although we should answer here the questions posed, those questions often contain parts that are better ignored. – false Jun 12 '15 at 12:23